java springboot rabbit mq如何消费
时间: 2023-07-18 12:40:07 浏览: 164
消费 RabbitMQ 中的消息需要以下步骤:
1. 在 Spring Boot 项目的 pom.xml 文件中添加 RabbitMQ 的依赖:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
```
2. 创建一个 RabbitMQ 连接工厂和一个消息监听器容器:
```
@Configuration
public class RabbitMQConfig {
@Bean
public ConnectionFactory connectionFactory() {
CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
connectionFactory.setHost("localhost");
connectionFactory.setPort(5672);
connectionFactory.setUsername("guest");
connectionFactory.setPassword("guest");
return connectionFactory;
}
@Bean
public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory() {
SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
factory.setConnectionFactory(connectionFactory());
factory.setMessageConverter(new Jackson2JsonMessageConverter());
return factory;
}
}
```
3. 创建一个消息监听器:
```
@Component
public class MessageListener {
@RabbitListener(queues = "myQueue")
public void handleMessage(String message) {
System.out.println("Received message: " + message);
}
}
```
4. 启动应用程序,监听器将自动连接到 RabbitMQ 服务器并开始消费队列中的消息。
当然,这只是 RabbitMQ 消费的基本步骤,实际应用中还需要考虑到消息确认、重试等问题。
阅读全文