springboot整合activeMQ
- 安装activeMQ
下载地址:http://activemq.apache.org/
解压
进入解压后的目录运行 ./bin/activemq start
启动后activemq会启动两个端口:
8161是activemq的管理页面,默认的账号密码都是admin
61616是程序连接activemq的通讯地址
-
引入依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-activemq</artifactId> </dependency>
3.修改application.yml
spring:
activemq:
#ActiveMQ通讯地址
broker-url: tcp://localhost:61616
#用户名
user: admin
#密码
password: admin
#是否启用内存模式(就是不安装MQ,项目启动时同时启动一个MQ实例)
in-memory: false
packages:
#信任所有的包
trust-all: true
pool:
#是否替换默认的连接池,使用ActiveMQ的连接池需引入的依赖
enabled: false
4.配置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") ;
}
}
5.创建消费者
@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);
}
}
6.创建生产者
@RestController
public class Producer {
@Autowired
private JmsMessagingTemplate jmsTemplate;
@Autowired
private Queue queue;
@Autowired
private Topic topic;
//发送queue类型消息
@GetMapping("/queue")
public void sendQueueMsg(String msg){
jmsTemplate.convertAndSend(queue, msg);
}
//发送topic类型消息
@GetMapping("/topic")
public void sendTopicMsg(String msg){
jmsTemplate.convertAndSend(topic, msg);
}
}
- 启动程序测试
浏览器中输入http://localhost:8080/queue?msg=hello
控制台:接收到queue消息:hello
浏览器中输入http://localhost:8080/topic?msg=hello
控制台:接收到topic消息:hello