springboot rabbitmq拉模式消费消息
时间: 2023-07-20 21:30:24 浏览: 112
在 Spring Boot 中使用 RabbitMQ 拉模式消费消息,需要进行以下步骤:
1. 引入 RabbitMQ 依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
```
2. 配置 RabbitMQ 连接信息:
```properties
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
```
3. 创建消息监听器:
```java
@Component
public class MyMessageListener {
@Autowired
private RabbitTemplate rabbitTemplate;
@RabbitListener(queues = "my_queue")
public void onMessage() {
Message message = rabbitTemplate.receive("my_queue");
if (message != null) {
String body = new String(message.getBody(), StandardCharsets.UTF_8);
System.out.println("Received message: " + body);
}
}
}
```
4. 配置消息监听器容器:
```java
@Configuration
public class MyRabbitConfig {
@Autowired
private ConnectionFactory connectionFactory;
@Autowired
private MyMessageListener myMessageListener;
@Bean
public SimpleMessageListenerContainer messageListenerContainer() {
SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.setQueueNames("my_queue");
container.setMessageListener(myMessageListener);
return container;
}
}
```
以上就是使用 RabbitMQ 拉模式消费消息的步骤,需要注意的是,拉模式消费消息需要手动调用 `RabbitTemplate.receive()` 方法获取消息。
阅读全文