Springboot 整合ActiveMQ 消息发布和订阅

Springboot 整合ActiveMQ 消息发布和订阅

1.maven依赖

		<!--activemq的依赖-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-activemq</artifactId>
    </dependency>

2.配置application.yml MQ连接信息


spring:
 activemq:
   broker-url: tcp://XXX.XXX.XXX.XXX:62626
   in-memory: false  #是否启用内存模式(也就是不安装MQ,项目启动时同时也启动一个MQ实例)
   packages:
     trust-all: true  	#信任所有的包
 jms:
   pub-sub-domain: true #如果是点对点(queue),那么此处默认应该是false,如果发布订阅,那么一定设置为true

如果是点对点(queue),那么此处默认应该是spring.jms.pub-sub-domain=false,如果发布订阅,那么一定设置
spring.jms.pub-sub-domain=true
如果直接发送对象消息,那么必须设置spring.activemq.packages.trust-all为true;另外如果你想开始消息持久化就必须spring.activemq.in-memory=false选项。

3.发布代码编写

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.core.JmsMessagingTemplate;
 
/**
 *订阅模式的生产者
 **/
@Configuration
public class TopicProducter {
 
    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;
 
    /**
     * @Description 将接受到的消息及消息模式(topic或queue)放到队列里面,然后消费
     * 者只需要正确的添加注解@JmsListener(destination = "目的地"),监听队列消息就会主动获取
     * @Param destination 目的地
     * @Param msg 消息
     * @Date  2019/3/21 14:46
     */
    public void sendMessage(String msg){
        ActiveMQTopic destination = new ActiveMQTopic("topic-my");
        jmsMessagingTemplate.convertAndSend(destination,msg);
    }
 
 
}
 

4订阅模式消费者

import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;
 
/**
 * 订阅模式消费者
 */
@Component
public class TopicCustomer {
    /**
     * 创建2个消费者
     * @param text
     */
    @JmsListener(destination = "topic-my")
    public void subscriber(String text) {
        System.out.println("消费者1111111111111111111111消费+"+text);
    }
 
    @JmsListener(destination = "topic-my")
    public void subscriber1(String text) {
        System.out.println("消费者2222222222222222222222消费+"+text);
    }
 
}	

import com.study.demo.activemq.TopicProducter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
/**
 * 订阅模式生产者
 */
@RestController
public class TopicController {
 
    @Autowired
    private TopicProducter topicProducter;
 
    @RequestMapping("/publish")
    public String publish(String msg){
        topicProducter.sendMessage(msg);
        return "消息已经发布";
    }
 
}

最后检验结果

1>.启动Activemq

2>.启动springboot

3>.访问http://127.0.0.1:10909/publish?msg=发送消息

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值