记 ==> 首次使用rabbitMQ优化项目
昨天刚学习完了rabbitMQ,刚好我的项目有个模块挺符合使用rabbitMQ进行异步处理的。
后续B再发帖子,直接推送到A的收件箱
接下来看看我的代码,(ps:本人小白勿喷)
当用户取关后,从用户收件箱内移除掉被取关博主的帖子
修改代码~~
引入AMQP依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency>
yml内添加rabbitmq配置
更改序列化规则,后续消息使用map发送
写一个config,配置一下交互机,队列,并完成绑定
然后写两个方法分别接听拉取帖子和取消帖子这两个queue
拉取队列
取关队列
我把源码贴出来,献丑啦
package com.brrbaii.config; import org.springframework.amqp.core.*; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import static com.brrbaii.common.MQConstants.*; @Configuration public class MQConfig { //拉取blog队列 @Bean public Queue pullBlogQueue(){ System.out.println("为什么没给我创建队列?"); return new Queue(PULL_BLOG_QUEUE); } //移出blog队列 @Bean public Queue pushBlogQueue(){ return new Queue(PUSH_BLOG_QUEUE); } //声明交换机 @Bean public DirectExchange blogDirectExchange(){ return new DirectExchange(DIRECT_EXCHANGE_BLOG); } @Bean public Binding pullBlogBinding(Queue pullBlogQueue, DirectExchange blogDirectExchange){ return BindingBuilder .bind(pullBlogQueue) .to(blogDirectExchange) .with(PULL_BLOG_ROUTING_KEY); } @Bean public Binding pushBlogBinding(Queue pushBlogQueue, DirectExchange blogDirectExchange){ return BindingBuilder .bind(pushBlogQueue) .to(blogDirectExchange) .with(PUSH_BLOG_ROUTING_KEY); } }