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!");  
        };  
    }  
}
相关推荐
han_hanker12 小时前
springboot 不推荐使用@Autowired怎么处理
java·spring boot·后端
最初的↘那颗心12 小时前
LangChain4j入门:集成SpringBoot与核心概念全解析
java·spring boot·ai·大模型·langchain4j
计算机学姐12 小时前
基于SpringBoot的高校实验室预约管理系统
java·spring boot·后端·mysql·spring·信息可视化·tomcat
于先生吖13 小时前
基于 SpringBoot 架构,高性能 JAVA 动漫短剧系统源码
java·开发语言·spring boot
斌味代码14 小时前
SpringBoot 3 实战:虚拟线程、全局异常处理与 JWT 鉴权完整方案
java·spring boot·后端
總鑽風14 小时前
数据一致性springcloud+rabbitmq+mysql+redis
mysql·spring cloud·rabbitmq
RInk7oBjo15 小时前
spring boot3--自动配置与手动配置
java·spring boot·后端
MacroZheng15 小时前
又一款企业级文件管理系统诞生了!支持万能文件在线预览,太香了!
java·spring boot·后端
Flittly15 小时前
【SpringAIAlibaba新手村系列】(12)RAG 检索增强生成技术
java·人工智能·spring boot·spring·ai
小胖java15 小时前
音乐推荐系统
java·spring boot