SpringBoot 整合ActiveMQ 小Demo

来源:互联网 发布:ubuntu无法拖拽复制 编辑:程序博客网 时间:2024/06/06 06:50

之前介绍过JMS基本概念,我们介绍了JMS的两种消息模型:点对点和发布订阅模型,以及消息被消费的两个方式:同步和异步,JMS编程模型的对象,最后说了JMS的优点。
- 下面用ActiveMQ为大家实现一种点对点的消息模型, 本文使用的是SpringBoot 集成的,只需要一个消息生成者和消息消费者;
- application.yml 里配置activemq

spring.activemq.broker-url=tcp://localhost:61616spring.activemq.in-memory=truespring.activemq.pool.enabled=false
  • 生产者类
public class Producer {    @Autowired // 也可以注入JmsTemplate,JmsMessagingTemplate对JmsTemplate进行了封装    private JmsMessagingTemplate jmsTemplate;    // 发送消息,destination是发送到的队列,message是待发送的消息    public void sendMessage(Destination destination, final String message){        jmsTemplate.convertAndSend(destination, message);    }}
  • 消费者类
@Componentpublic class Consumer {    // 使用JmsListener配置消费者监听的队列,其中text是接收到的消息    @JmsListener(destination = "mytest.queue")    public void receiveQueue(String text) {        System.out.println("Consumer收到的报文为:" + text);    }}
  • test类
@RunWith(SpringRunner.class)@SpringBootTestpublic class ProducerTest {    @Autowired    private Producer producer;    @Test    public void contextLoads() throws InterruptedException {        Destination destination = new ActiveMQQueue("mytest.queue");        for(int i=0; i<100; i++){            producer.sendMessage(destination, "myname is zhaokang!!!");        }    }}
原创粉丝点击