本文共 2424 字,大约阅读时间需要 8 分钟。
org.springframework.boot spring-boot-starter-activemq
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选项。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); } }
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/