Spring Boot 3 中如何创建一个 RabbitMQ 消息消费者?
时间: 2024-12-23 20:21:56 浏览: 10
在Spring Boot 3中创建一个RabbitMQ消息消费者,你可以按照以下步骤操作:
1. **添加依赖**:
首先,在你的`pom.xml`文件中添加Spring AMQP和RabbitMQ的依赖:
```xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
</dependencies>
```
2. **配置RabbitMQ**:
在`application.properties`或`application.yml`中配置RabbitMQ的相关信息,如连接地址、队列名称等:
```properties
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=myuser
spring.rabbitmq.password=mypassword
```
3. **创建消费者组件**:
创建一个`RabbitConfig`类用于声明消息接收者(Listener Container)和消费者(Consumer):
```java
@Configuration
public class RabbitConfig {
@Autowired
private ConnectionFactory connectionFactory;
@Bean
public TaskExecutor taskExecutor() {
return new SimpleAsyncTaskExecutor();
}
@RabbitListener(queues = "${rabbitmq.queue.name}")
public void handleMessage(String message) {
System.out.println("Received message: " + message);
}
}
```
这里假设你的消息队列名为`myqueue`。
4. **启动监听器容器**:
如果你想在启动时自动启动消费者,可以将`@EnableRabbit`注解添加到启动类上:
```java
@SpringBootApplication
@EnableRabbit
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
```
阅读全文