1、核心的启动器包
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency>
2、配置 yml
spring:
rabbitmq:
host: 192.168.0.103
username: guest
password: guest
virtual-host: /
3、消费端监听器对象及Rabbitmq的注解
@Component
public class Listener {
@RabbitListener(bindings = @QueueBinding(
value = @Queue(value = "spring.test.queue", durable = "true"),
exchange = @Exchange(
value = "spring.test.exchange",
ignoreDeclarationExceptions = "true",
type = ExchangeTypes.TOPIC
),
key = {"#.#"}))
public void listen(String msg){
System.out.println("接收到消息:" + msg);
}
}
4、生产方同样上面导依赖和yml配置,在需要发消息的时候注入AmqpTemplate使用
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class MqDemo {
@Autowired
private AmqpTemplate amqpTemplate;
@Test
public void testSend() throws InterruptedException {
String msg = "hello, Spring boot amqp";
this.amqpTemplate.convertAndSend("spring.test.exchange","a.b", msg);
// 等待10秒后再结束
Thread.sleep(10000);
}
}
消费方消费方法里面有异常了抛出,这样出了异常消息不会被消费丢失,而是退回消息中间件queue中
本文详细介绍了如何在Spring Boot项目中整合RabbitMQ,包括核心依赖的引入、YAML配置、消费端监听器的实现及注解使用,以及生产者发送消息的方法。通过示例代码展示了如何创建队列、交换机并进行绑定,以及如何使用AmqpTemplate进行消息的发送和接收。
795

被折叠的 条评论
为什么被折叠?



