Spring Boot 实现 RabbitMQ 监听消息的几种方式
Spring Boot实现RabbitMQ监听消息主要有以下几种方式:
- 使用
@RabbitListener
注解
@Component
public class Listener {
@RabbitListener(queues = "myQueue")
public void processMessage(String content) {
System.out.println("Received Message: " + content);
}
}
- 使用
MessageListenerAdapter
@Component
public class Listener {
@RabbitListener(queues = "myQueue")
public void processMessage(String content) {
System.out.println("Received Message: " + content);
}
@Bean
MessageListenerAdapter listenerAdapter(Receiver receiver) {
return new MessageListenerAdapter(receiver, "handleMessage");
}
public static class Receiver {
public void handleMessage(String content) {
System.out.println("Received Message: " + content);
}
}
}
- 使用
@RabbitHandler
注解
@Component
public class Listener {
@RabbitHandler
public void processMessage(String content) {
System.out.println("Received Message: " + content);
}
}
- 使用
MessageListener
接口
@Component
public class Listener implements MessageListener {
@Override
public void onMessage(Message message) {
String content = new String(message.getBody());
System.out.println("Received Message: " + content);
}
}
在Spring Boot的配置文件中(application.properties或application.yml),你需要配置RabbitMQ的连接信息,例如主机名、端口、用户名、密码等。
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
确保你的Spring Boot应用程序已经添加了RabbitMQ的依赖。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
以上方法都需要在类或者方法上标注@Component
注解,以便Spring Boot可以自动扫描并注册为Bean。在实际使用时,你可以根据具体需求选择合适的方式来实现RabbitMQ的消息监听。
评论已关闭