当前位置: 首页 > news >正文

SpringBoot整合RabbitMQ(Java注解方式配置)

1.生产端

1. 创建生产者SpringBoot工程

  2. 引入start,依赖坐标

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

  3. 编写yml配置,基本信息配置

spring:rabbitmq:host:公网ipport:5671username: password:virtual-host:

  4. 定义交换机,队列以及绑定关系的Config配置类

@Configuration
public class RabbitMqConfig {//定义交换机的名字public static final String  EXCHANGE_NAME = "boot_topic_exchange";//定义队列的名字public static final String QUEUE_NAME = "boot_queue";//1、声明交换机@Bean("bootExchange") //bean声明,加入到容器中public Exchange bootExchange(){//topicExchange: 主题交换机 durable:是否持久化//ExchangeBuilder工具类调用topicExchange的API方法创建主题交换机return ExchangeBuilder.topicExchange(EXCHANGE_NAME).durable(true).build();}//2、声明队列@Bean("bootQueue")public Queue bootQueue(){return QueueBuilder.durable(QUEUE_NAME).build();}//3、队列与交换机进行绑定@Beanpublic Binding bindQueueExchange(@Qualifier("bootQueue") Queue queue, @Qualifier("bootExchange") Exchange exchange){return BindingBuilder.bind(queue).to(exchange).with("boot.#").noargs();}}

  5. 注入RabbitTemplate,调用方法,完成消息发送

@SpringBootTest
@RunWith(SpringRunner.class)
public class ProducerTest {//注入 RabbitTemplate@Autowiredprivate RabbitTemplate  rabbitTemplate;@Testpublic void send(){rabbitTemplate.convertAndSend("boot_topic_exchange","boot.haha","boot mq...");}
}

2.消费端 

1. 创建消费者SpringBoot工程

  2. 引入start,依赖坐标

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

  3. 编写yml配置,基本信息配置

spring:rabbitmq:host:公网ipport:5671username: password:virtual-host:

  4. 定义监听类,使用@RabbitListener注解完成队列监听。

@Component //声明这是一个组件
public class RabbitMQListener {//定义方法进行信息的监听   RabbitListener中的参数用于表示监听的是哪一个队列//如果有消息过来,就会执行这个方法,自动会把消息封装到Message对象中,取走消息之后会在队列里删除掉消息@RabbitListener(queues = "boot_queue")public void ListenerQueue(Message message){System.out.println("message:"+message.getBody());}
}

3.启动流程

先点击生产端的@test方法发送信息到队列中去,然后直接运行消费端的

@SpringBootApplication启动方法

相关文章:

  • android-ndk开发(3): 连接设备到开发机
  • Java面试:微服务与大数据场景下的技术挑战
  • 模块方法模式(Module Method Pattern)
  • scroll-view高度自适应
  • 线程池配置不合理:系统性能的隐形杀手(深度解析版)
  • SpringCloud多环境配置的一些问题
  • 基于 HTML5 的贪吃蛇小游戏实现
  • PE文件结构(导出表)
  • Linux 系统下VS Code python环境配置!
  • Cisco NDO - Nexus Dashboard Orchestrator
  • 六、shell脚本--正则表达式:玩转文本匹配的“万能钥匙”
  • Dify网页版 + vllm + Qwen
  • 论文报错4
  • Ubuntu安装编译环境
  • JookDB:一款国产的通用数据库开发工具
  • 网络传输中字节序
  • PostgreSQL 的 pg_current_wal_lsn 函数
  • Pinia状态管理工具速成
  • 【NLP】 28. 语言模型的评估方式:MRR, PERPLEXITY, BLEU, WER从困惑度到实际效果
  • C++ 类与对象(下)—— 进阶特性与底层机制解析(构造函数初始化,类型转换,static成员,友元,内部类,匿名对象)
  • 许昌市场监管部门对胖东来玉石开展日常检查:平均毛利率不超20%
  • 专访|刘伟强:在《水饺皇后》里,我放进儿时全家福照片
  • 旭辉控股集团:去年收入477.89亿元,长远计划逐步向轻资产业务模式转型
  • 五一期间全国高速日均流量6200万辆,同比增长8.1%
  • 人民日报评论员:因势利导对经济布局进行调整优化
  • 铁路上海站今日预计发送旅客65.8万人次,同比增长超16%