spring boot集成activeMQ
引入依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-activemq</artifactId> </dependency>
配置activeMq:
spring: activemq: broker-url: tcp://127.0.0.1:61616 in-memory: true pool: enabled: false
开启jms:
@SpringBootApplication @EnableJms public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
spring boot中点对点模型处理消息:
配置queue:
@Bean public Queue queue() { return new ActiveMQQueue("sample.queue"); }
消息生产者:
@Component public class Producer { @Autowired private JmsMessagingTemplate jmsMessagingTemplate; @Autowired private Queue queue; public void send(String msg) { this.jmsMessagingTemplate.convertAndSend(this.queue, msg); } }
消息消费者:
@Component public class Consumer { @JmsListener(destination = "sample.queue") public void receiveQueue(String text) { System.out.println("消费消息:" + text); } }
测试接口:
@RestController public class MsgController { @Autowired private Producer producer; /** * 测试点对点模型消息生产与消费 */ @GetMapping("/send/{msg}") public String send(@PathVariable String msg) { producer.send(msg); return "success"; } }
发送请求:
控制台输出:
spring boot中一对多模型处理消息:
@Component public class Consumer { @JmsListener(destination = "sample.queue") public void receiveQueue(String text) { System.out.println("消费消息:" + text); } @JmsListener(destination = "sample.queue") public void receiveQueue2(String text) { System.out.println("消费消息2:" + text); } }
spring boot中发布订阅模型处理消息:
配置topic:
@Bean public Topic topic() { return new ActiveMQTopic("sample.topic"); }
生产者:
@Component public class Producer2 { @Autowired private JmsMessagingTemplate jmsMessagingTemplate; @Autowired private Topic topic; public void send(String msg) { this.jmsMessagingTemplate.convertAndSend(this.topic, msg); } }
消费者:
@Component public class Consumer2 { /** * 3个消费者都可以收到同一个消息 */ @JmsListener(destination = "sample.topic") public void receiveTopic1(String text) { System.out.println("订阅消息1" + text); } @JmsListener(destination = "sample.topic") public void receiveTopic2(String text) { System.out.println("订阅消息2" + text); } @JmsListener(destination = "sample.topic") public void receiveTopic3(String text) { System.out.println("订阅消息3" + text); } }
修改配置:
不用的时候要注释起来
spring: activemq: broker-url: tcp://127.0.0.1:61616 in-memory: true pool: enabled: false #发布订阅模型(一个项目只支持一种模式) jms: pub-sub-domain: true
测试接口:
/** * 测试发布订阅模型消息生产与消费 */ @GetMapping("/send2/{msg}") public String send2(@PathVariable String msg) { producer2.send(msg); return "success"; }
观察结果: