spring boot 集成 +activeMQ
下载安装 activeMQ
-
下载地址
本机在window下下载,下载后执行/bin/win64/activemq.bat
- 打开地址 管理台地址 默认账户admin/admin
spring 中集成
- 在pom文件中添加
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
</dependency>
- 添加application.yml 配置
spring:
activemq:
broker-url: tcp://127.0.0.1:61616
user: admin
password: admin
- 创建创造者
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Service;
import javax.jms.Destination;
/**
*
* 模拟ActiveMQ生产者
* 发送方式见Test测试类
* @Author 林育池
*/
@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);
}
}
- 创建监听者
import com.alibaba.fastjson.JSON;
import com.plusesb.document.LogDocument;
import com.plusesb.service.EsbSearchService;
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 EsbLogListener {
@Autowired
private EsbSearchService esbSearchService;
/**
*
*
* @param
*/
@JmsListener(destination = "esblog")
public void getEsbLog(String message) {
log.info("收到的消息是:" + message);
LogDocument logDocument = JSON.parseObject(message,LogDocument.class);
esbSearchService.save(logDocument);
}
}
- 创建简单测试
import com.plusesb.activemq.Producer;
import org.apache.activemq.command.ActiveMQQueue;
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("esblog");
// String info = "测试activeMQ Topic消息!";
String info1 = "{ \"serviceReqId\":\"S02\", \"serviceCode\":\"S01\", \"serviceName\":\"S01\", \"logException\":{ \"serviceReqId\":\"S01\", \"serviceCode\":\"S01\", \"serviceName\":\"S01\" } }";
// producer.sendMessage(destination, info);
producer.sendMessage(destination1, info1);
}
}
网友评论