ActiveMQ 与 Springboot 的集成

 

1. 引入依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-activemq</artifactId>
            <version>2.1.5.RELEASE</version>
        </dependency>

 

2. application.properties 中书写相关配置

server.port=8081
spring.activemq.broker-url=tcp://192.168.174.8888:61616
spring.activemq.user=admin
spring.activemq.password=admin

#默认是false,为true开启发布订阅模式,同时点对点模式失效
spring.jms.pub-sub-domain=false   

 

3. 相关代码

ActiveMqConf.java

@Component
public class ActiveMqConf {

    @Autowired
    private JmsTemplate jmsTemplate;

    //发送队列消息
    public void sendQueueMsg(String destination,String msg) {
        jmsTemplate.convertAndSend(destination, msg);
    }

    //发布订阅消息
    public void sendTopicMsg(String destinationMsg,String msg){
        Destination destination = new ActiveMQTopic(destinationMsg);
        jmsTemplate.convertAndSend(destination,msg);
    }

}
ConsumerListener.java
@Component
public class ConsumerListener {

    //监听 springboot-queue
    @JmsListener(destination = "springboot-queue")
    public void consumer1(Message message){
        TextMessage textMessage = (TextMessage) message;
        System.out.println("监听到的消息:  "+textMessage);

    }

    //监听 springboot-topic
    @JmsListener(destination = "springboot-topic")
    public void consumer2(Message message){
        TextMessage textMessage = (TextMessage) message;
        System.out.println("监听到的Topic消息:   "+textMessage);
    }

    @Bean
    public Destination getDestination(){
        Destination destination = new ActiveMQTopic("springboot-topic");
        return destination;
    }

}
ActiveMqController.java
@RestController
@RequestMapping("queue")
public class ActiveMqController {

    @Autowired
    ActiveMqConf activeMqConf;

    //发布queue
    @RequestMapping("send")
    public void send(String destination,String msg){
        activeMqConf.sendQueueMsg(destination,msg);
    }

    //发布Topic
    @RequestMapping("sendTopic")
    public void sendTopic(String destination,String msg){
        activeMqConf.sendTopicMsg(destination,msg);
    }
}

4. 启动application,测试结果

(1)浏览器访问:

http://localhost:8081/queue/send?destination=springboot-queue&msg=xiaopang

ConsumerListener一直在监听着相关订阅的发布,一旦监听到了订阅的发布,则立即执行 consumer 的代码

(2)浏览器访问:

http://localhost:8081/queue/sendTopic?destination=springboot-topic&msg=xiaohei

发现控制台什么也没有打印,也就是没有监听到,原因是配置文件这个属性要改为true

#默认是false,为true开启发布订阅模式,同时点对点模式失效
spring.jms.pub-sub-domain=true

改完重新启动,再次访问,控制台就要监听到的消息了

 

注意:改配置文件只能同时使用 queue 或者 topic 其中一种模式,两者不能同时使用,如果要配置同时使用,参考这篇博客

         解决Springboot整合ActiveMQ发送和接收topic消息的问题

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值