在 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 项目
创建项目的步骤以往的文章都有详细步骤,这里不再细说。
选择合适的依赖 Spring for RabbitMQ
和 Spring Boot DevTools
(用于开发时的热部署),其他需要的依赖也可以自行添加,比如Spring Web,Lombok等。
IDEA 将自动创建并初始化项目。
2. 添加 RabbitMQ 依赖
通常,通过 Spring Initializr 创建的项目已经包含了 Spring for RabbitMQ
依赖。如果没有,可以手动添加:
在 pom.xml
中添加以下依赖:
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 的连接信息:
properties
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
中添加:
properties
spring.rabbitmq.template.default-receive-queue=myQueue
spring.rabbitmq.template.exchange=myExchange
spring.rabbitmq.template.routing-key=myRoutingKey
4. 编写生产者和消费者代码
4.1 创建 RabbitMQ 配置类
首先,创建一个配置类,用于声明队列、交换器和绑定:
java
package com.example.springforrabbitmq.configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
/**
* @author zhizhou 2024/9/3 23:10
*/
@Configuration
public class RabbitMQConfig {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Value("${spring.rabbitmq.host}")
private String host;
@Value("${spring.rabbitmq.port}")
private int port;
@Value("${spring.rabbitmq.username}")
private String username;
@Value("${spring.rabbitmq.password}")
private String password;
@Value("${spring.rabbitmq.virtual-host}")
private String virtualhost;
public static final String QUEUE_NAME = "myQueue";
public static final String EXCHANGE_NAME = "myExchange";
@Bean
public Queue queue() {
return new Queue(QUEUE_NAME, false);
}
@Bean
public TopicExchange exchange() {
return new TopicExchange(EXCHANGE_NAME);
}
@Bean
public Binding binding(Queue queue, TopicExchange exchange) {
return BindingBuilder.bind(queue).to(exchange).with("routing.key.#");
}
@Bean
public ConnectionFactory connectionFactory() {
CachingConnectionFactory connectionFactory = new CachingConnectionFactory(host, port);
connectionFactory.setUsername(username);
connectionFactory.setPassword(password);
connectionFactory.setVirtualHost(virtualhost);
return connectionFactory;
}
@Bean
public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
return rabbitTemplate;
}
}
4.2 编写消息生产者
接下来,编写一个服务类,发送消息到 RabbitMQ:
java
package com.example.springforrabbitmq.service;
import com.example.springforrabbitmq.configuration.RabbitMQConfig;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @author zhizhou 2024/9/3 23:11
*/
@Service
public class MessageProducer {
@Autowired
private RabbitTemplate rabbitTemplate;
public void sendMessage(String message) {
rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME, "routing.key.test", message);
System.out.println("Message Sent: " + message);
}
}
4.3 编写消息消费者
创建一个消费者类,处理从 RabbitMQ 接收的消息:
java
package com.example.springforrabbitmq.service;
import com.example.springforrabbitmq.configuration.RabbitMQConfig;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;
/**
* @author zhizhou 2024/9/3 23:12
*/
@Service
public class MessageConsumer {
@RabbitListener(queues = RabbitMQConfig.QUEUE_NAME)
public void receiveMessage(String message) {
System.out.println("Message Received: " + message);
}
}
5. 编写和运行测试
5.1 编写测试类
编写一个简单的测试类来测试消息的发送和接收:
java
package com.example.springforrabbitmq;
import com.example.springforrabbitmq.service.MessageProducer;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
/**
* @author zhizhou 2024/9/3 23:13
*/
@SpringBootTest
public class RabbitMQIntegrationTest {
@Autowired
private MessageProducer messageProducer;
@Test
public void testSendMessage() {
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的异同点,为什么面试经常问到实现原理?