SpringAMQP是SpringBoot操作 RabbitMQ的包
1.创建一个空项目并创建一个生产者的Module
2.导入依赖
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-amqp --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> <version>2.4.2</version> </dependency>
3.创建一个application.yml文件:
spring: rabbitmq: host: 127.0.0.1 port: 5672 username: guest password: guest virtual-host: / server: port: 8081
4.创建一个Rabbit的配置类
package com.ckfuture.amqpsend.config; import org.springframework.amqp.core.Binding; import org.springframework.amqp.core.BindingBuilder; import org.springframework.amqp.core.Queue; import org.springframework.amqp.core.TopicExchange; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * @author CKFuture * @since 1.0.0 */ @Configuration public class RabbitMQConfig { //声明队列 @Bean public Queue queue(){ return new Queue("amqp_queue"); } //声明交换机 @Bean public TopicExchange topicExchange(){ return new TopicExchange("amqp_exchange"); } //绑定交换机和队列 @Bean public Binding binding(){ return BindingBuilder.bind(queue()).to(topicExchange()).with("*.amqp.#"); } }
5.编写生产者代码:
package com.ckfuture.amqpsend; import org.junit.jupiter.api.Test; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class AmqpSendApplicationTests { @Test void contextLoads() { } @Autowired private RabbitTemplate rabbitTemplate; @Test public void testSend(){ String message="Hello"; System.out.println("发送消息:"+message); //发送消息 (交互机,路由,消息) rabbitTemplate.convertAndSend("amqp_exchange","test.amqp",message); } }
6.创建一个消费者RecvInit.java编写发送代码:
package com.ckfuture.amqprecv; import org.springframework.amqp.rabbit.annotation.RabbitHandler; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; @Component //监听队列 @RabbitListener(queues="amqp_queue") public class RecvInit { //监听之后获取消息的处理方法 @RabbitHandler public void testRecv(String message){ System.out.println("接收到消息"+message); } }
7.运行生产者
在管理控制台查看:
8.运行消费者程序
在管理控制台查看:
总结:
① 创建配置类,声明 队列、交互机、绑定交互机和队列,在绑定的时候要使用通配符绑定路由key
② 正常发送消息是通过RabbitTemplate.convertAndSed()方法发送消息。
③ 消费者(接收者)只需要通过@RabbitListener(queues="队列名")监听队列和@RabbitHandler监听之后获取消息的处理方法
整个项目结构:
RabbitMQ 参考:https://www.bilibili.com/video/BV1Ky4y1D7Yv?p=2&spm_id_from=pageDriver