springboot整合activemq
1.pom依赖
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.fengshun</groupId> <artifactId>consumer</artifactId> <version>1.0-SNAPSHOT</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.0.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-activemq</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> </project>
2.application.yml配置文件
spring: activemq: #ActiveMQ通讯地址 broker-url: tcp://192.168.1.193:61616 #用户名 user: admin #密码 password: admin #是否启用内存模式(就是不安装MQ,项目启动时同时启动一个MQ实例) in-memory: false packages: #信任所有的包 trust-all: true pool: #是否替换默认的连接池,使用ActiveMQ的连接池需引入的依赖 enabled: false server: port: 9072
3.创建activeMQ配置类
package fengshun.comfig; import org.apache.activemq.command.ActiveMQQueue; import org.apache.activemq.command.ActiveMQTopic; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jms.annotation.EnableJms; import org.springframework.jms.config.DefaultJmsListenerContainerFactory; import org.springframework.jms.config.JmsListenerContainerFactory; import javax.jms.ConnectionFactory; import javax.jms.Queue; import javax.jms.Topic; /** * activeMQ配置类 */ @Configuration @EnableJms public class ActiveMQConfig { @Bean public Queue queue() { return new ActiveMQQueue("springboot.queue") ; } //springboot默认只配置queue类型消息,如果要使用topic类型的消息,则需要配置该bean @Bean public JmsListenerContainerFactory jmsTopicListenerContainerFactory(ConnectionFactory connectionFactory){ DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory(); factory.setConnectionFactory(connectionFactory); //这里必须设置为true,false则表示是queue类型 factory.setPubSubDomain(true); return factory; } @Bean public Topic topic() { return new ActiveMQTopic("springboot.topic") ; } }
4.消费者
package fengshun.consumer; import org.springframework.jms.annotation.JmsListener; import org.springframework.stereotype.Component; /** * @Date: 2019/10/24 * 消费者 */ @Component public class Consumer { //接收queue类型消息 //destination对应配置类中ActiveMQQueue("springboot.queue")设置的名字 @JmsListener(destination="springboot.queue") public void ListenQueue(String msg){ System.out.println("接收到queue消息:" + msg); } //接收topic类型消息 //destination对应配置类中ActiveMQTopic("springboot.topic")设置的名字 //containerFactory对应配置类中注册JmsListenerContainerFactory的bean名称 @JmsListener(destination="springboot.topic", containerFactory = "jmsTopicListenerContainerFactory") public void ListenTopic(String msg){ System.out.println("接收到topic消息:" + msg); } }