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 小时前
基于javaweb的SpringBoot爱游旅行平台设计和实现(源码+文档+部署讲解)
java·spring boot·后端
qq_12498707531 小时前
原生小程序+springboot+vue医院医患纠纷管理系统的设计与开发(程序+论文+讲解+安装+售后)
java·数据库·spring boot·后端·小程序·毕业设计
伊成2 小时前
一文详解Spring Boot如何配置日志
java·spring boot·单元测试
bing_1582 小时前
Spring Boot 的自动配置为 Spring MVC 做了哪些事情?
spring boot·spring·mvc
嘵奇5 小时前
Spring Boot中HTTP连接池的配置与优化实践
spring boot·后端·http
椰椰椰耶5 小时前
【RabbitMQ】工作队列和发布/订阅模式的具体实现
分布式·rabbitmq·ruby
Persistence___6 小时前
SpringBoot中的拦截器
java·spring boot·后端
嘵奇6 小时前
Spring Boot 跨域问题全解:原理、解决方案与最佳实践
java·spring boot·后端
堕落年代7 小时前
SpringBoot的单体和分布式的任务架构
spring boot·分布式·架构
码农飞哥7 小时前
互联网大厂Java求职面试实战:Spring Boot与微服务场景深度解析
java·数据库·spring boot·安全·微服务·消息队列·互联网医疗