publisher-comfirm--type:correlated
时间: 2024-09-27 22:07:47 浏览: 33
Jquery-Comfirm提示框
在Spring Boot集成RabbitMQ时,使用publisher-confirm(发布者确认)功能可以增强消息的可靠性和准确性。其中,`type: correlated`意味着每个发布的消息都会有一个唯一的标识符,称为“correlation id”,它关联到接收方的响应。当消息被成功确认时,这个correlation id会被用于找到相应的响应。
1. **开启Publisher Confirms**:在发送消息时,你需要设置`publisher-confirms`为true,这会在发送消息后等待接收确认:
```java
rabbitTemplate.setPublisherReturns(true);
rabbitTemplate.setPublisherConfirmations(true);
```
2. **设置correlationId**:每条发送的消息都应该包含一个`correlationId`,以便于后续验证。可以在消息头或正文里设置:
```java
Map<String, Object> headers = new HashMap<>();
headers.put("correlation-id", someUniqueId); // 替换为生成的实际唯一ID
String routingKey = ...;
Object payload = ...;
rabbitTemplate.convertAndSend("exchangeName", routingKey, payload, headers);
```
3. **监听确认和拒绝**:创建一个监听器来处理来自消费者的确认或拒绝(negative acknowledgment)。消费者需要设置`consumerCancelled`属性为true,以便监听取消请求:
```java
@Bean
public SimpleMessageListenerContainer listenerContainer() {
SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
container.setConnectionFactory(rabbitConnectionFactory());
container.setQueueNames("confirmQueue");
container.setMessageConverter(converter());
container.setConfirmCallback(new RabbitAdminConfirmedCallbackAdapter() {
@Override
public void confirmed(String correlationId, boolean multiple) {
System.out.println("Received confirmation for correlationId: " + correlationId);
}
@Override
public void rejected(String correlationId, String rejectionReason, Throwable cause) {
System.err.println("Rejected with reason: " + rejectionReason);
}
});
return container;
}
```
阅读全文