springboot整合rabbitmq 实现消息发送和消费

Spring Boot提供了RabbitMQ的自动化配置,使得整合RabbitMQ变得非常容易。

首先,需要在pom.xml文件中引入amqp-client和spring-boot-starter-amqp依赖:

xml 复制代码
<dependency>
    <groupId>com.rabbitmq</groupId>
    <artifactId>amqp-client</artifactId>
    <version>5.5.1</version>
</dependency>

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

接下来需要在application.properties文件中配置RabbitMQ连接信息:

properties 复制代码
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
spring.rabbitmq.virtual-host=/

然后编写消息发送者:

java 复制代码
@Component
public class RabbitMQSender {
    private final RabbitTemplate rabbitTemplate;

    public RabbitMQSender(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
    }

    public void send(String message) {
        rabbitTemplate.convertAndSend("my-exchange", "my-routing-key", message);
    }
}

其中,my-exchange和my-routing-key是需要自己定义的交换机和路由键。

最后编写消息消费者:

java 复制代码
@Component
public class RabbitMQReceiver {
    @RabbitListener(queues = "my-queue")
    public void receive(String message) {
        System.out.println("Received message: " + message);
    }
}

其中,my-queue也是需要自己定义的队列。

在以上步骤完成后,即可实现消息的发送和消费。

相关推荐
招风的黑耳39 分钟前
我用SpringBoot撸了一个智慧水务监控平台
java·spring boot·后端
大佐不会说日语~40 分钟前
Spring AI Alibaba 的 ChatClient 工具注册与 Function Calling 实践
人工智能·spring boot·python·spring·封装·spring ai
Miss_Chenzr43 分钟前
Springboot优卖电商系统s7zmj(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
数据库·spring boot·后端
程序员游老板43 分钟前
基于SpringBoot3+vue3的爱心陪诊平台
java·spring boot·毕业设计·软件工程·课程设计·信息与通信
期待のcode1 小时前
Springboot核心构建插件
java·spring boot·后端
Miss_Chenzr1 小时前
Springboot旅游景区管理系统9fu3n(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
数据库·spring boot·旅游
五阿哥永琪2 小时前
Spring Boot 中自定义线程池的正确使用姿势:定义、注入与最佳实践
spring boot·后端·python
canonical_entropy3 小时前
Nop入门:增加DSL模型解析器
spring boot·后端·架构
计算机毕设VX:Fegn08955 小时前
计算机毕业设计|基于springboot + vue图书借阅管理系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
undsky_5 小时前
【RuoYi-SpringBoot3-Pro】:接入 AI 对话能力
人工智能·spring boot·后端·ai·ruoyi