本文共 3519 字,大约阅读时间需要 11 分钟。
新建Maven工程
pom.xml4.0.0 org.example sprinboot_activemq 1.0-SNAPSHOT org.springframework.boot spring-boot-starter-parent 2.1.5.RELEASE UTF-8 1.8 1.8 org.springframework.boot spring-boot-starter org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-activemq 2.1.5.RELEASE org.springframework.boot spring-boot-starter-test org.springframework.boot spring-boot-maven-plugin
springboot配置:
application.ymlserver: port: 6666spring: activemq: broker-url: tcp://localhost:61616 #自己的MQ服务器地址 user: admin password: admin jms: pub-sub-domain: true # false: Queue true:Topic#自己定义主题名称mytopic: boot-activemq-topic
配置Bean:
package pers.zhang.config;import org.apache.activemq.command.ActiveMQTopic;import org.springframework.beans.factory.annotation.Value;import org.springframework.context.annotation.Bean;import org.springframework.stereotype.Component;import javax.jms.Topic;@Componentpublic class TopicConfigBean { @Value("${mytopic}") private String topicName; @Bean public Topic topic(){ return new ActiveMQTopic(topicName); }}
生产者:
@Componentpublic class Topic_Produce { @Autowired private JmsMessagingTemplate jmsMessagingTemplate; @Autowired private Topic topic; @Scheduled(fixedDelay = 2000) public void produceTopic(){ jmsMessagingTemplate.convertAndSend(topic, "主题消息:" + UUID.randomUUID().toString().substring(0, 6)); System.out.println("2秒一次..."); }}
主启动类:
@SpringBootApplication@EnableScheduling//开启public class MainApp_Produce { public static void main(String[] args) { SpringApplication.run(MainApp_Produce.class, args); }}
创建Maven工程,pom.xml与上面生产者一致
springboot配置,application.yml:
server: port: 5566spring: activemq: broker-url: tcp://localhost:61616 #自己的MQ服务器地址 user: admin password: admin jms: pub-sub-domain: true # false: Queue true:Topic#自己定义队列名称mytopic: boot-activemq-topic
消费者:
package pers.zhang.activemq;import org.springframework.jms.annotation.JmsListener;import org.springframework.stereotype.Component;import javax.jms.JMSException;import javax.jms.TextMessage;@Componentpublic class Queue_Consumer { @JmsListener(destination = "${mytopic}") public void receive(TextMessage textMessage)throws JMSException { System.out.println("消费者收到主题的消息:" + textMessage.getText()); }}
主启动类:
@SpringBootApplicationpublic class MainApp_Consumer { public static void main(String[] args) { SpringApplication.run(MainApp_Consumer.class, args); }}
先启动消费者:
再启动生产者,每2秒发送一条消息:
消费者控制台打印:
消费者收到主题的消息:主题消息:dfccdd消费者收到主题的消息:主题消息:70b401消费者收到主题的消息:主题消息:ce22bd消费者收到主题的消息:主题消息:997932
转载地址:http://ybpqb.baihongyu.com/