spring boot 集成ActiveMQ
昨天刚调通了kafka,工作原因 大多从事传统项目,实战比较少,今天学习一下ActiveMQ。 构建spring-boot工程请参照其他
- ActiveMQ安装
1.官方下载地址 http://activemq.apache.org/download.html
2.apache-activemq-5.15.3\bin\win64\activeMQ.bat
3.浏览器输入http://127.0.0.1:8161 官方默认账户密码 admin/admin - maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
</dependency>
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-pool</artifactId>
</dependency>
- properties配置
spring.activemq.broker-url=tcp://localhost:61616
spring.activemq.in-memory=true
spring.activemq.pool.enabled=false
##如果此处设置为true,需要加如下的依赖包,否则会自动配置失败,报JmsMessagingTemplate注入失败
- 生产者
package com.chinasofti.mq;
import javax.jms.Destination;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Service;
@Service("producer")
public class Producer {
@Autowired // 也可以注入JmsTemplate,JmsMessagingTemplate对JmsTemplate进行了封装
private JmsMessagingTemplate jmsTemplate;
// 发送消息,destination是发送到的队列,message是待发送的消息
public void sendMessage(Destination destination, final String message){
jmsTemplate.convertAndSend(destination, message);
}
}
- 消费者
package com.chinasofti.mq;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;
@Component
public class Consumer {
// 使用JmsListener配置消费者监听的队列,其中text是接收到的消息
@JmsListener(destination = "mytest.queue")
public void receiveQueue(String text) {
System.out.println("Consumer收到的报文为:"+text);
}
}
- Junit测试部分代码
@Autowired
private Producer producer;
@Test
public void contextLoads() throws InterruptedException {
Destination destination = new ActiveMQQueue("mytest.queue");
for(int i=0; i<100; i++){
producer.sendMessage(destination, "一个Mq消息");
}
}
- 执行结果