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: true
创建生产者工程的启动类 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 sendMessage() {
template.convertAndSend("message-topic", "学习消息队列的朋友们,大家好!");
}
}
此时,先不要着急运行生产者相关的代码!
消费者
创建一个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-topic")
public void receiveMessage(Message message) {
if (message instanceof TextMessage) {
TextMessage textMessage = (TextMessage) message;
try {
System.out.println("接收到的消息是: " + textMessage.getText());
} catch (JMSException e) {
e.printStackTrace();
}
}
}
}
由于这是发布-订阅模式,所以我们首先要运行消费者
运行 消费者的 ConsumerApplication.java
消费者成功启动后,再启动生产者
以JUNIT的方式 运行 生产者的 测试类 SpringBootProcuder.java
在生产者启动成功后,消费者就接收到消息