本篇博客将根据一个示例,介绍ActiveMQ和SpringBoot的综合使用,在这里我们也会分别队列模式和主题模式进行说明。
SpringBoot与ActiveMQ结合(上) ActiveMQ介绍与使用
修改POM文件
在pom.xml增加对ActiveMQ的相关jar包的引用:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
</dependency>
队列模式
修改application.properties
增加spring.activemq.broker-url=tcp://localhost:61616 用来设置broker-url
在Application类添加Queue的返回实现
@SpringBootApplication
public class SpringBootMqApplication extends SpringBootServletInitializer{
@Autowired
JmsTemplate jmsTemplate;
@Bean
public Queue getQueue() {
return new ActiveMQQueue("my-destination");
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(SpringBootMqApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(SpringBootMqApplication.class, args);
}
}
创建Controller作为消息生产者
@RestController
public class SendMsgController {
@Autowired
JmsTemplate jmsTemplate;
@Autowired
Queue queue
@RequestMapping("/sendMsg")
public String sendMsg(@RequestParam String msg) {
jmsTemplate. convertAndSend (queue,msg);
return "success";
}
}
这里就是调用localhost:8080/sendMsg?msg=发送的消息文字 就会向目的地为queue代表的队列 发送一条文字为msg的值的信息。
消费者接收信息
在其他SpringBoot项目或者本项目添加如下类(注意项目的application.properties中不能设置spring.jms.pub-sub-domain=true否则将不能接收queue模式消息)
@Component
public class Receiver {
@JmsListener(destination="my-destination")
public void receivedMessage(String message) {
System.out.println("接收到"+message);
}
}
这样一个注解JmsListener 和 Destination(目的地)属性 就让这个方法变为 能从目的地为my-destination的消息队列取消息进行处理的方法了。
启动项目 然后调用controller,就会发现 在消费者处确实接收到了消息。
主题模式
application.properties修改
同队列模式 添加url即可
在Application类添加返回Topic的Bean方法
@Bean
public Topic getTopic() {
return new ActiveMQTopic("topic-msg");
}
创建Controller作为消息发布者
public class SendMsgController {
@Autowired
JmsTemplate jmsTemplate
@Autowired
Topic topic
@RequestMapping("/sendMsgTopic")
public String sendMsgTopic(@RequestParam String msg) {
jmsTemplate. convertAndSend (topic,msg);
return "success";
}
@JmsListener(destination="topic-success")
public void receivedHandleMessageTopicSuccess(String message) {
System.out.println(message);
}
}
订阅者接受消息
因为SpringBoot中ActiveMQ默认 不指定发送信息模式 和监听信息模式 的话,那么就会使用队列模式,所以这里 要在订阅者的项目application.properties指定:
spring.jms.pub-sub-domain=true
但是要注意,设置了此属性为true,如果没做其他处理,那么此项目中只能消费主题模式的消息。这里我没有找到一个能让消费者/订阅者项目既能收到主题模式消息又能收到队列模式消息的简单设置方式。上篇博客的简单Java实现方式的消费者/订阅者应该是可以让一个SringBoot项目同时处理两种模式的消息(未验证,有兴趣的同学可以验证一下),但是这种处理感觉耦合度比较高,如果有同学有更好的处理方式可以告诉我。
@JmsListener(destination="topic-msg")
@SendTo({"topic-success"})
public String receivedMessageTopic(String message) {
System.out.println("接收到Topic"+message);
return "接收并处理了Topic消息";
}
这里增加了@SendTo 在 处理完成之后 会把返回值对象 作为 目的是topic-success 的信息发送出去。我们之前在消息发布者Controller处 定义一个receivedHandleMessageTopicSuccess方法,这个方法会收到消息订阅者处理之后返回的 “接收并处理了Topic消息”。
@SendTo返回的是队列模式 还是 主题模式 是和 处理的信息是队列模式还是主题模式有关的,即它们是保持一致的。(自己测试得出,未进行深层验证)