0


SpringBoot 依赖之 Spring for RabbitMQ

在 IntelliJ IDEA 中创建 Spring Boot 项目并调试 Spring for RabbitMQ 的完整流程。

概念

Spring for RabbitMQ
  • 依赖名称: Spring for RabbitMQ
  • 功能描述: Gives your applications a common platform to send and receive messages, and your messages a safe place to live until received.
  • 中文释义:为您的应用程序提供一个发送和接收消息的通用平台,并为您的消息提供一个安全的存放位置,直到收到为止。

集成:

1. 创建 Spring Boot 项目

创建项目的步骤以往的文章都有详细步骤,这里不再细说。
如参考:
SpringBoot 依赖之Spring Web

选择合适的依赖

Spring for RabbitMQ

Spring Boot DevTools

(用于开发时的热部署),其他需要的依赖也可以自行添加,比如Spring Web,Lombok等。
IDEA 将自动创建并初始化项目。

2. 添加 RabbitMQ 依赖

通常,通过 Spring Initializr 创建的项目已经包含了

Spring for RabbitMQ

依赖。如果没有,可以手动添加:

pom.xml

中添加以下依赖:

<dependencies><!-- Spring Boot Starter for RabbitMQ --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-amqp</artifactId></dependency><!-- Spring Boot DevTools (Optional for Hot Reload) --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><scope>runtime</scope><optional>true</optional></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><!-- JUnit for testing --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.springframework.amqp</groupId><artifactId>spring-rabbit-test</artifactId><scope>test</scope></dependency></dependencies>

3. 配置 RabbitMQ

src/main/resources/application.properties

中,配置 RabbitMQ 的连接信息:

spring.application.name=spring-for-rabbitmq

spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
spring.rabbitmq.virtual-host: /mirror  #virtual-host起隔离作用,默认为:/
#自定义配置
spring.rabbitmq.template.default-receive-queue=myQueue
spring.rabbitmq.template.exchange=myExchange
spring.rabbitmq.template.routing-key=myRoutingKey

如果你有自定义的队列、交换器等配置,也可以在

application.properties

中添加:

spring.rabbitmq.template.default-receive-queue=myQueue
spring.rabbitmq.template.exchange=myExchange
spring.rabbitmq.template.routing-key=myRoutingKey

4. 编写生产者和消费者代码

4.1 创建 RabbitMQ 配置类

首先,创建一个配置类,用于声明队列、交换器和绑定:

packagecom.example.springforrabbitmq.configuration;importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;importorg.springframework.amqp.core.Binding;importorg.springframework.amqp.core.BindingBuilder;importorg.springframework.amqp.core.Queue;importorg.springframework.amqp.core.TopicExchange;importorg.springframework.amqp.rabbit.connection.CachingConnectionFactory;importorg.springframework.amqp.rabbit.connection.ConnectionFactory;importorg.springframework.amqp.rabbit.core.RabbitTemplate;importorg.springframework.beans.factory.annotation.Value;importorg.springframework.beans.factory.config.ConfigurableBeanFactory;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.context.annotation.Scope;/**
 * @author zhizhou   2024/9/3 23:10
 */@ConfigurationpublicclassRabbitMQConfig{privatefinalLogger logger =LoggerFactory.getLogger(this.getClass());@Value("${spring.rabbitmq.host}")privateString host;@Value("${spring.rabbitmq.port}")privateint port;@Value("${spring.rabbitmq.username}")privateString username;@Value("${spring.rabbitmq.password}")privateString password;@Value("${spring.rabbitmq.virtual-host}")privateString virtualhost;publicstaticfinalStringQUEUE_NAME="myQueue";publicstaticfinalStringEXCHANGE_NAME="myExchange";@BeanpublicQueuequeue(){returnnewQueue(QUEUE_NAME,false);}@BeanpublicTopicExchangeexchange(){returnnewTopicExchange(EXCHANGE_NAME);}@BeanpublicBindingbinding(Queue queue,TopicExchange exchange){returnBindingBuilder.bind(queue).to(exchange).with("routing.key.#");}@BeanpublicConnectionFactoryconnectionFactory(){CachingConnectionFactory connectionFactory =newCachingConnectionFactory(host, port);
        connectionFactory.setUsername(username);
        connectionFactory.setPassword(password);
        connectionFactory.setVirtualHost(virtualhost);return connectionFactory;}@BeanpublicRabbitTemplaterabbitTemplate(ConnectionFactory connectionFactory){RabbitTemplate rabbitTemplate =newRabbitTemplate(connectionFactory);return rabbitTemplate;}}
4.2 编写消息生产者

接下来,编写一个服务类,发送消息到 RabbitMQ:

packagecom.example.springforrabbitmq.service;importcom.example.springforrabbitmq.configuration.RabbitMQConfig;importorg.springframework.amqp.rabbit.core.RabbitTemplate;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Service;/**
 * @author zhizhou   2024/9/3 23:11
 */@ServicepublicclassMessageProducer{@AutowiredprivateRabbitTemplate rabbitTemplate;publicvoidsendMessage(String message){
        rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME,"routing.key.test", message);System.out.println("Message Sent: "+ message);}}
4.3 编写消息消费者

创建一个消费者类,处理从 RabbitMQ 接收的消息:

packagecom.example.springforrabbitmq.service;importcom.example.springforrabbitmq.configuration.RabbitMQConfig;importorg.springframework.amqp.rabbit.annotation.RabbitListener;importorg.springframework.stereotype.Service;/**
 * @author zhizhou   2024/9/3 23:12
 */@ServicepublicclassMessageConsumer{@RabbitListener(queues =RabbitMQConfig.QUEUE_NAME)publicvoidreceiveMessage(String message){System.out.println("Message Received: "+ message);}}

5. 编写和运行测试

5.1 编写测试类

编写一个简单的测试类来测试消息的发送和接收:

packagecom.example.springforrabbitmq;importcom.example.springforrabbitmq.service.MessageProducer;importorg.junit.jupiter.api.Test;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.boot.test.context.SpringBootTest;/**
 * @author zhizhou   2024/9/3 23:13
 */@SpringBootTestpublicclassRabbitMQIntegrationTest{@AutowiredprivateMessageProducer messageProducer;@TestpublicvoidtestSendMessage(){
        messageProducer.sendMessage("Hello, 兔子宝宝🐰!");}}
5.2 运行测试

运行

Run 'RabbitMQIntegrationTest'

,测试方法将会启动并发送一条消息到 RabbitMQ。一般来讲我们会在控制台中查看消息发送和接收的日志输出。

6. 调试和热部署

Spring Boot DevTools 提供了热部署的功能,在开发过程中可以自动重新加载修改后的代码。至于热部署的配置可以参阅之前的文章

SpringBoot依赖之Spring Boot DevTools热部署开发增效工具

  • 启动项目,进行开发,代码修改保存后,DevTools 会自动重启应用。

7. 运行和查看效果

启动 Spring Boot 应用程序,确保 RabbitMQ 正在运行。你可以使用

RabbitMQ Management

插件或其他工具监控消息的发送和接收情况。

8. 总结

至此我们已经实现了在 IntelliJ IDEA 中创建 Spring Boot 项目,并集成并调试 Spring for RabbitMQ依赖包。依靠Spring成熟的生态,我们可以根据自己业务的实际需求进一步扩展功能,比如添加更多复杂的消息处理逻辑、错误处理和重试机制等。

扩展:
我们也可以思考下RabbitMQ 和RocketMQ的异同点,为什么面试经常问到实现原理?


本文转载自: https://blog.csdn.net/ahauedu/article/details/141874560
版权归原作者 ahauedu 所有, 如有侵权,请联系我们删除。

“SpringBoot 依赖之 Spring for RabbitMQ”的评论:

还没有评论