1. 创建生产者和消费者两个服务
2. 引入依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId>spring-rabbit-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
3. 配置文件
server.port=10086
spring.rabbitmq.host=192.168.56.129
spring.rabbitmq.port=5672
spring.rabbitmq.username=lisi
spring.rabbitmq.password=lisi
spring.rabbitmq.virtual-host=/lisi
server.port=10085
spring.rabbitmq.host=192.168.56.129
spring.rabbitmq.port=5672
spring.rabbitmq.username=lisi
spring.rabbitmq.password=lisi
spring.rabbitmq.virtual-host=/lisi
# none-不开启生产者确认 simple-阻塞方式确认 correlated-非阻塞监听方式确认
spring.rabbitmq.publisher-confirm-type=correlated
# 确认消息是否到达队列
spring.rabbitmq.publisher-returns=true
4. 消费者监听
@Component
public class ConsumerListener {
@RabbitListener(bindings = @QueueBinding(
value = @Queue(value = "spring.test.queue"),
exchange = @Exchange(value = "spring.test.exchange", ignoreDeclarationExceptions = "true", type = ExchangeTypes.TOPIC),
key = {"a.*"}
))
public void test(String msg) {
System.out.println("msg: " + msg);
}
}
5. 生产者发送消息队列
@SpringBootTest
class ProducerDemoApplicationTests {
@Autowired
private RabbitTemplate rabbitTemplate;
@Test
void contextLoads() {
this.rabbitTemplate.convertAndSend("spring.test.exchange", "a.b", "hello rabbitmq...");
}
}
6. 手动ack响应
@Configuration
@Slf4j
public class RabbitConfig {
@Autowired
private RabbitTemplate rabbitTemplate;
@PostConstruct
public void init() {
// 确认消息是否到达交换机,不管是否到达都会执行
this.rabbitTemplate.setConfirmCallback((@Nullable CorrelationData correlationData, boolean ack, @Nullable String cause) -> {
if (ack) {
System.out.println("消息到达了交换机!");
} else {
System.out.println("消息没有到达交换机:" + cause);
}
});
// 确认消息是否到达队列,只有没有到达队列才会执行
this.rabbitTemplate.setReturnCallback((Message message, int replyCode, String replyText, String exchange, String routingKey) -> {
log.error("消息没有到达队列。交换机:{},路由键:{},消息内容:{},回调编码:{},回调文本:{}",
exchange, routingKey, new String(message.getBody()), replyCode, replyText);
});
}
}