目录
SpringAMQP是什么
为什么采用SpringAMQP
SpringAMQP应用
准备springBoot工程
实现消息发送
SpringAMQP是什么
Spring AMQP是Spring框架下用于简化AMQP(高级消息队列协议)应用开发的一套工具集,主要针对RabbitMQ等消息中间件的集成。它提供了基于模板的消息发送和接收方法(如AmqpTemplate),以及用于配置和管理交换机、队列及其绑定关系的机制。通过Spring AMQP,开发者可以方便地将消息队列功能整合到Spring项目中。
为什么采用SpringAMQP
将来我们开发业务功能的时候,肯定不会在控制台收发消息,而是应该基于编程的方式。RabbitMQ官方提供的Java客户端编码相对复杂,一般生产环境下我们更多会结合Spring来使用。而Spring的官方刚好基于RabbitMQ提供了这样一套消息收发的模板工具:SpringAMQP。并且还基于SpringBoot对其实现了自动装配,使用起来非常方便。
SpringAMQP提供了三个功能:
1.自动声明队列、交换机及其绑定关系
2.基于注解的监听器模式,异步接收消息
3.封装了RabbitTemplate工具,用于发送消息
SpringAMQP应用
准备springBoot工程
新建一个springboot工程,包括三部分:
-
mq-demo:父工程,管理项目依赖
-
publisher:消息的发送者
-
consumer:消息的消费者
工程目录如图所示:
pom.xml文件导入依赖:
<?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>cn.itcast.demo</groupId><artifactId>mq-demo</artifactId><version>1.0-SNAPSHOT</version><modules><module>publisher</module><module>consumer</module></modules><packaging>pom</packaging><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.7.12</version><relativePath/></parent><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target></properties><dependencies><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency><!--AMQP依赖,包含RabbitMQ--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-amqp</artifactId></dependency><!--单元测试--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId></dependency></dependencies>
</project>
如此,子工程中就可以直接使用SpringAMQP。
实现消息发送
首先配置MQ地址,在publisher
服务的application.yml和
consumer
服务的application.yml
中添加配置:
spring:rabbitmq:host: 192.168.12.101 # 你的虚拟机IPport: 5672 # 端口virtual-host: /user # 你的虚拟主机username: user # 用户名password: 123 # 密码
然后在publisher
服务中编写测试类SpringAmqpTest
,并利用RabbitTemplate
实现消息发送:
@SpringBootTest
class SpringAmqpTest {@Autowiredprivate RabbitTemplate rabbitTemplate;@Testpublic void testSimpleQueue() {// 队列名称String queueName = "hello.queue";// 消息String message = "hello rabbitmq";// 发送消息rabbitTemplate.convertAndSend(queueName, message);}
}
运行后,打开控制台,可以看到消息已经发送到队列中:
当然,我们可以在consumer
服务的consumer.listener
包中新建一个类SpringRabbitListener来接收
,代码如下:
@Component
@Slf4j
public class SpringRabbitListener {@RabbitListener(queues = "hello.queue")public void listenSimpleQueue(String msg) {log.info("消费者收到消息:{}", msg);}
}
启动ConsumerApplication,控制台显示如下:
解读:实现SpringAMQP对RabbitMQ的消息收发的测试。