Spring Boot 集成ActiveMQ
使用ActiveMQ版本5.14.0套菜,spring Boot版本1.5.9账蓉;
1歪脏、向pom.xml 文件中添加依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
2、application.yml添加配置
消費者接受queue消息遥巴,需要將pub-sub-domain配置為false
spring:
jms:
pub-sub-domain: true #false默認(rèn)不接受topic消息千康,而是接受隊列queue消息
activemq:
broker-url: tcp://172.17.1.25:61616
in-memory: true
enabled: false
3、生產(chǎn)者producer
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Service;
import javax.jms.Destination;
/**
*
* 模擬ActiveMQ生產(chǎn)者
* 發(fā)送方式見Test測試類
* @Author 孫龍
*/
@Service("producer")
public class Producer {
@Autowired // 也可以注入JmsTemplate挪哄,JmsMessagingTemplate對JmsTemplate進行了封裝
private JmsMessagingTemplate jmsTemplate;
// 發(fā)送消息吧秕,destination是發(fā)送到的隊列,message是待發(fā)送的消息
public void sendMessage(Destination destination, final String message){
jmsTemplate.convertAndSend(destination, message);
}
}
4迹炼、消費者Consumer
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;
@Slf4j
@Component
public class CarDataListener {
/**
* 接收通過車輛信息
*
* @param carDataInfo
*/
@JmsListener(destination = "activetest")
public void getPassInfo(String message) {
log.info("收到的消息是:" + message);
}
}
5砸彬、測試queue和topic
package com.lilian;
import com.lilian.jms.Producer;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.jms.Destination;
@RunWith(SpringRunner.class)
@SpringBootTest
public class CommMQApplicationTests {
@Autowired
private Producer producer;
@Test
public void contextLoads() {
Destination destination = new ActiveMQTopic("activetest");
// Destination destination1 = new ActiveMQQueue("activetest");
String info = "測試activeMQ Topic消息!";
// String info1 = "測試activeMQ Queue消息斯入!";
producer.sendMessage(destination, info);
// producer.sendMessage(destination1, info1);
}
}
6砂碉、消息可視化
ActiveMQ的服務(wù)器地址加上8161端口。例如: localhost:8161
隨后我會將自己寫的Demo整理出來開源到github上刻两,在這里公開地址增蹭,希望能夠幫助到你!