博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Springboot 整合ActiveMQ 消息发布和订阅
阅读量:4131 次
发布时间:2019-05-25

本文共 2424 字,大约阅读时间需要 8 分钟。

Springboot 整合ActiveMQ 消息发布和订阅

文章目录

1.maven依赖

org.springframework.boot
spring-boot-starter-activemq

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; /** *订阅模式的生产者 **/@Configurationpublic 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; /** * 订阅模式消费者 */@Componentpublic 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; /** * 订阅模式生产者 */@RestControllerpublic class TopicController {
@Autowired private TopicProducter topicProducter; @RequestMapping("/publish") public String publish(String msg){
topicProducter.sendMessage(msg); return "消息已经发布"; } }

最后检验结果

1>.启动Activemq

2>.启动springboot

3>.访问发送消息

转载地址:http://ugbvi.baihongyu.com/

你可能感兴趣的文章
Valid Palindrome 简单的回文判断
查看>>
对话周鸿袆:从程序员创业谈起
查看>>
web.py 0.3 新手指南 - 如何用Gmail发送邮件
查看>>
web.py 0.3 新手指南 - RESTful doctesting using app.request
查看>>
LeetCode第46题思悟——全排列(permutations)
查看>>
驱动力3.0,动力全开~
查看>>
记CSDN访问量10万+
查看>>
Linux下Oracle数据库账户被锁:the account is locked问题的解决
查看>>
记CSDN访问20万+
查看>>
Windows 环境下Webstorm 2020.3 版本在右下角找不到Git分支切换部件的一种解决方法
查看>>
Electron-Vue项目中遇到fs.rm is not a function问题的解决过程
查看>>
飞机换乘次数最少问题的两种解决方案
查看>>
有向无回路图的理解
查看>>
设计模式中英文汇总分类
查看>>
WPF实现蜘蛛纸牌游戏
查看>>
单例模式
查看>>
数据结构之树
查看>>
二叉树非递归遍历算法思悟
查看>>
红黑树算法思悟
查看>>
实例区别BeanFactory和FactoryBean
查看>>