SpringBoot 整合ActiveMQ 小Demo

之前介紹過JMS基本概念,我們介紹了JMS的兩種消息模型:點對點和發佈訂閱模型,以及消息被消費的兩個方式:同步和異步,JMS編程模型的對象,最後說了JMS的優點。
- 下面用ActiveMQ爲大家實現一種點對點的消息模型, 本文使用的是SpringBoot 集成的,只需要一個消息生成者和消息消費者;
- application.yml 裏配置activemq

spring.activemq.broker-url=tcp://localhost:61616
spring.activemq.in-memory=true
spring.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);
    }
}
  • 消費者類
@Component
public class Consumer {
    // 使用JmsListener配置消費者監聽的隊列,其中text是接收到的消息
    @JmsListener(destination = "mytest.queue")
    public void receiveQueue(String text) {
        System.out.println("Consumer收到的報文爲:" + text);
    }
}
  • test類
@RunWith(SpringRunner.class)
@SpringBootTest
public 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!!!");
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章