SpringBoot整合Activemq (点对点模式)
生产者:
首先创建一个maven工程为 生产者
配置 生产者工程的 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.itheima.activemq</groupId>
<artifactId>springboot-procuder</artifactId>
<version>1.0-SNAPSHOT</version>
<!-- springboot 的父工程:锁定springboot的版本 以及其整合框架的版本-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.1.RELEASE</version>
<relativePath />
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- springboot与activemq的整合依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
</dependencies>
</project>
配置生产者工程的yml文件
server:
port: 9001 #端口
spring:
application:
name: activemq-procuder # 服务名称
# springboot 与 activemq 整合配置
activemq:
broker-url: tcp://192.168.115.134:61616 #连接地址
user: admin # activemq的用户名
password: admin # activemq的密码
# 指定发送方式 (点对点为 false 发布订阅为 true)
jms:
pub-sub-domain: false
创建生产者工程的启动类 ProcuderApplication.java
/**
* 生产者的启动类
*/
@SpringBootApplication
public class ProcuderApplication {
public static void main(String[] args) {
SpringApplication.run(ProcuderApplication.class, args);
}
}
最后,创建测试类,并启动该测试类,以 点对点的方式,来发送一条消息
/**
* 演示SpringBoot 与 activemq 整合 - 消息生产者
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = ProcuderApplication.class)
public class SpringBootProcuder {
/**
* JmsMessagingTemplate 用户工具类发送消息
*/
@Autowired
private JmsMessagingTemplate template;
@Test
public void p2pSender() {
template.convertAndSend("message-p2p", "学习消息队列的朋友们,大家好!");
}
}
此时,消息已成功发送!
消费者
创建一个maven工程为 消费者
配置 消费者工程的 pom文件
(依赖内容同生产者的内容,直接复制粘贴即可)
创建消费者启动类 ConsumerApplication.java
@SpringBootApplication
public class ConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerApplication.class, args);
}
}
最后,创建一个接收消息的类,类中带有接收消息的方法,用户接收消息
@Component
public class MsgListener {
/**
* 用户接收消息的方法
* destination: 队列的名称或者主题的名称
* @param message
*/
@JmsListener(destination = "message-p2p")
public void receiveMessage(Message message) {
if (message instanceof TextMessage) {
TextMessage textMessage = (TextMessage) message;
try {
System.out.println("接收到的消息是: " + textMessage.getText());
} catch (JMSException e) {
e.printStackTrace();
}
}
}
}
最后,启动消费者工程的启动类,即可以点对点的发方式,接收生产者发送过来的消息!