import org.springframework.amqp.AmqpException;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate.ConfirmCallback;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
public class MySender {
private static final String EXCHANGE_NAME = "exchange";
private static final String ROUTING_KEY = "routingKey";
private final RabbitTemplate rabbitTemplate;
private final CountDownLatch latch;
public MySender() {
ConnectionFactory connectionFactory = new CachingConnectionFactory("localhost");
rabbitTemplate = new RabbitTemplate(connectionFactory);
latch = new CountDownLatch(1);
rabbitTemplate.setConfirmCallback(new ConfirmCallback() {
public void confirm(CorrelationData correlationData, boolean ack, String cause) {
if (ack) {
System.out.println("Message confirmed: " + correlationData.getId());
latch.countDown(); // 标记确认回调执行完成
} else {
System.out.println("Message not confirmed: " + correlationData.getId() + " - " + cause);
// 在 handleNack 中进行消息重发等处理
// ...
}
}
});
}
public void send(String message) throws MyException {
CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
try {
rabbitTemplate.convertAndSend(EXCHANGE_NAME, ROUTING_KEY, message, correlationData);
latch.await(); // 等待确认回调执行完成
System.out.println("Message sent to consumer: " + message);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new MyException("Message send failed: " + correlationData.getId(), e);
} catch (AmqpException e) {
System.out.println("Message send failed, correlationData: " + correlationData);
// 在 convertAndSend 方法中发生异常时,也需要进行消息重发等处理
// ...
throw new MyException("Message send failed: " + correlationData.getId(), e);
}
}
public static class MyException extends Exception {
public MyException(String message, Throwable cause) {
super(message, cause);
}
}
}
使用了 CountDownLatch 类来实现等待确认回调函数执行完成后再发送消息给消费者的功能。具体实现方式如下:
在 MySender 构造函数中创建 CountDownLatch 对象,并将初始计数器设置为 1。
在 setConfirmCallback 回调函数中,如果消息得到了确认,我们调用 CountDownLatch 对象的 countDown 方法来将计数器减一,标记确认回调执行完成。
在 send 方法中,我们先调用 convertAndSend 方法来发送消息,并使用 latch.await() 方法来等待确认回调函数执行完成。
当确认回调函数执行完成后,latch.await() 方法返回,我们就可以将消息发送给消费者。
在这个示例代码中,我们在 send 方法中捕获了 InterruptedException 和 AmqpException 异常,并将它们封装到自定义异常 MyException 中抛出。同时,我们在 InterruptedException 捕获块中重新设置中断标志,以便上层调用者能够知道线程被中断了。
如果消息发送失败,我们抛出 MyException 异常,并在异常消息中包含消息的 CorrelationData ID,以便后续的错误处理能够定位到具体的消息。