在Spring Boot项目中集成RabbitMQ消息中间件

Spring Boot集成RabbitMQ并引入spring-boot-starter-amqp的详细步骤和说明:

引入依赖

在pom.xml文件中添加spring-boot-starter-amqp依赖:

xml 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

添加这个依赖后,Maven会自动下载并包含所有必要的依赖库,包括Spring AMQP和RabbitMQ的客户端库。

配置RabbitMQ

在application.properties或application.yml文件中配置RabbitMQ的连接信息,例如:

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

这些配置信息用于指定RabbitMQ服务器的地址、端口、用户名和密码。Spring Boot会自动读取这些配置并创建相应的连接工厂。

使用RabbitTemplate发送消息

RabbitTemplate是Spring AMQP提供的一个用于发送消息的模板类。您可以通过注入RabbitTemplate的Bean来使用它发送消息到指定的队列或交换机。例如:

java 复制代码
@Autowired
private RabbitTemplate rabbitTemplate;
 
public void sendMessage(String queueName, String message) {
    rabbitTemplate.convertAndSend(queueName, message);
}

使用@RabbitListener接收消息

@RabbitListener注解用于标记一个方法作为消息监听器,当指定的队列或主题中有消息时,该方法会被自动调用。例如:

java 复制代码
@Component
public class MessageListener {
 
    @RabbitListener(queues = "myQueue")
    public void receiveMessage(String message) {
        System.out.println("Received message: " + message);
    }
}

Spring Boot会自动配置SimpleMessageListenerContainer来监听myQueue队列,并将接收到的消息传递给MessageListener中的receiveMessage方法。

相关推荐
Carsene5 分钟前
Spring Boot 包扫描新姿势:AutoScan vs @Import vs @ComponentScan 深度对比
spring boot·后端
win x40 分钟前
RabbitMQ 七种工作模式
分布式·rabbitmq
hrhcode1 小时前
【java工程师快速上手go】三.Go Web开发(Gin框架)
java·spring boot·golang
Rick19931 小时前
Spring Boot自动装配原理
java·spring boot·后端
Devin~Y1 小时前
大厂内容社区面试实录:从 Spring Boot 微服务到 AI RAG 问答(附详细解析)
java·spring boot·redis·elasticsearch·spring cloud·微服务·kafka
我叫张土豆1 小时前
我把 Spring Boot 升级到 4.0.2 后,顺手重构了整个 AI 脚手架:删模块、加 Skills Agent、补 Resume RAG
人工智能·spring boot·重构
han_hanker2 小时前
Spring Boot 如何读取 application.yml 作为配置
java·spring boot·后端
计算机学姐2 小时前
基于SpringBoot的充电桩预约管理系统【阶梯电费+个性化推荐+数据可视化】
java·vue.js·spring boot·后端·mysql·信息可视化·mybatis
han_hanker2 小时前
Spring Boot 配置类注解@Configuration, @Bean
java·spring boot·后端