Spring Boot(十八):异步消息JMS(ActiveMQ)

介绍

pom文件引入:

1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
</dependency>

启用JMS注解:@EnableJms

mq配置:

1
2
3
4
5
6
7
8
9
import javax.jms.Queue;

@Configuration
public class JmsConfiguration {
@Bean
public Queue queue() {
return new ActiveMQQueue("dodd.queue");
}
}

实现类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Component
public class JmsComponent {
@Autowired
private JmsMessagingTemplate jmsMessagingTemplate;

@Autowired
private Queue queue;

public void send(String msg) {
this.jmsMessagingTemplate.convertAndSend(this.queue, msg);
}

@JmsListener(destination = "dodd.queue")
public void receiveQueue(String text) {
System.out.println("接受到:" + text);
}
}

配置文件:

1
2
#放在缓存中,不用连接真正的mq
spring.activemq.in-memory=true

测试类:

1
2
3
4
5
6
7
@Autowired
private JmsComponent jmsComponent;

@Test
public void send() {
jmsComponent.send("hello world");
}