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

SpringBoot项目嵌入RabbitMQ

在Spring Boot中嵌入RabbitMQ可以通过添加相应的依赖来完成。首先需要在pom.xml文件中引入spring-boot-starter-amqp依赖:

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

然后,在application.properties或者application.yml配置文件中设置RabbitMQ连接信息:

spring.rabbitmq.host=your_rabbitmq_hostname

spring.rabbitmq.port=5672

spring.rabbitmq.username=your_rabbitmq_username

spring.rabbitmq.password=your_rabbitmq_password

最后,创建消息发送者(Producer)和消息接收者(Consumer)类,并使用@Autowired注解将其自动装载到Spring容器中。示例如下:

  1. 创建消息发送者类:

import org.springframework.amqp.core.Queue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;
 
@Component
public class MessageSender {
    
    @Autowired
    private ApplicationContext context;
    
    public void send(String message) {
        Queue queue = (Queue) context.getBean("myQueue"); // 获取队列对象
        
        MessageChannel channel = context.getBean(queue.getName(), MessageChannel.class); // 根据队列名称获取消息通道
        
        channel.send(MessageBuilder.withPayload(message).build()); // 发送消息
    }
}

  1. 创建消息接收者类:

import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
 
@Component
public class MessageReceiver {
    
    @RabbitListener(queues = "myQueue") // 指定监听的队列名称
    public void receive(String message) {
        System.out.println("Received message: " + message);
    }
}

 当调用MessageSendersend()方法时,会向"myQueue"队列发送消息;

MessageReceiver则会监听该队列,并处理接收到的消息。

http://www.lryc.cn/news/305208.html

相关文章:

  • 提升网络质量:UDPspeeder 实现网络优化与提速
  • 为什么前端开发变得越来越复杂了?这可能是我们的错
  • VR系统的开发流程
  • 前端输入框校验限制不能输入中文
  • 强大的文本绘图——PlantUML
  • ES相关问题
  • 基于Linux直接安装的Nginx版本升级方法
  • 探索设计模式的魅力:状态模式揭秘-如何优雅地处理复杂状态转换
  • 力扣hot100题解(python版10-12题)
  • 【算法】复杂度分析
  • 车载电子测试学习内容
  • STM32F103x 的时钟源
  • 【电路笔记】-RC放电电路
  • 【C++STL】STL容器详解
  • 缓存篇—缓存雪崩
  • 力扣日记2.22-【回溯算法篇】47. 全排列 II
  • 如何理解三大微分中值定理
  • Linux--自定义shell
  • AIGC 实战:Ollama 和 Hugging Face 是什么关系?
  • Gitee教程2(完整流程)
  • Go 1.22 中的 for 循环新特性详解
  • igolang学习2,golang开发配置国内镜像
  • R语言空间分析、模拟预测与可视化
  • 体育赛事直播系统软件开发
  • 使用 kind 集群安装运行极狐GitLab Runner【上】
  • wine 源码 vk3d wine-gecko wine-mono 各版本 国内下载地址 中国科技技术大学源
  • 【ArcGIS微课1000例】0104:二位面状数据转三维多面体(建筑物按高度拉伸)
  • jquery简介与解析
  • Apache Commons开源的工具库介绍
  • SQL语法法则