springboot集成RabbitMQ

springboot集成RabbitMQ

  • [1. 添加 Maven 依赖](#1. 添加 Maven 依赖)
  • [2. 配置 RabbitMQ](#2. 配置 RabbitMQ)
  • [3. 创建消息生产者](#3. 创建消息生产者)
  • [4. 创建消息消费者](#4. 创建消息消费者)
  • [5. 运行和测试](#5. 运行和测试)

1. 添加 Maven 依赖

首先,你需要在你的 pom.xml 文件中添加 Spring Boot RabbitMQ Starter 的依赖。

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

2. 配置 RabbitMQ

在 application.properties 或 application.yml 文件中添加 RabbitMQ 的配置信息。

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

3. 创建消息生产者

创建一个服务类来发送消息到 RabbitMQ 队列。

java 复制代码
import org.springframework.amqp.rabbit.core.RabbitTemplate;  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.stereotype.Service;  
  
@Service  
public class MessageProducerService {  
  
    @Autowired  
    private RabbitTemplate rabbitTemplate;  
  
    public void sendMessage(String queueName, String message) {  
        rabbitTemplate.convertAndSend(queueName, message);  
    }  
}

4. 创建消息消费者

创建一个类来监听 RabbitMQ 队列并处理接收到的消息。

java 复制代码
import org.springframework.amqp.rabbit.annotation.RabbitListener;  
import org.springframework.stereotype.Component;  
  
@Component  
public class MessageConsumerService {  
  
    @RabbitListener(queues = "myQueue")  
    public void receiveMessage(String message) {  
        System.out.println("Received message: " + message);  
    }  
}

5. 运行和测试

创建一个简单的 REST API 或使用 Spring Boot 的命令行运行器来测试 RabbitMQ 的集成。

java 复制代码
import org.springframework.boot.CommandLineRunner;  
import org.springframework.boot.SpringApplication;  
import org.springframework.boot.autoconfigure.SpringBootApplication;  
import org.springframework.context.annotation.Bean;  
  
@SpringBootApplication  
public class RabbitmqApplication {  
  
    public static void main(String[] args) {  
        SpringApplication.run(RabbitmqApplication.class, args);  
    }  
  
    @Bean  
    public CommandLineRunner run(MessageProducerService producer) {  
        return args -> {  
            producer.sendMessage("myQueue", "Hello RabbitMQ!");  
        };  
    }  
}
相关推荐
白仑色1 小时前
Spring Cloud Gateway 实战指南
spring boot·微服务·路由转发·限流熔断
追风少年浪子彦8 小时前
mapstruct与lombok冲突原因及解决方案
java·spring boot·spring·spring cloud
军军君018 小时前
基于Springboot+UniApp+Ai实现模拟面试小工具四:后端项目基础框架搭建下
spring boot·spring·面试·elementui·typescript·uni-app·mybatis
白仑色10 小时前
完整 Spring Boot + Vue 登录系统
vue.js·spring boot·后端
MZ_ZXD00110 小时前
flask校园学科竞赛管理系统-计算机毕业设计源码12876
java·spring boot·python·spring·django·flask·php
小郭的学习日记12 小时前
互联网大厂Java面试:从Spring Boot到微服务的场景应用
spring boot·微服务·java面试·技术栈·电商平台
超级小忍12 小时前
在 Spring Boot 中使用 MyBatis 的 XML 文件编写 SQL 语句详解
xml·spring boot·mybatis
Q_Q196328847512 小时前
python的平安驾校管理系统
开发语言·spring boot·python·django·flask·node.js·php
超级小忍13 小时前
在 Spring Boot 中如何使用 Assert 进行断言校验
spring boot·后端