我有一个简单的工作队列案例,当发件人想要确认消息被激活或接收方没有。
private final static String QUEUE_NAME = "hello";
public static void main(String[] argv) throws Exception
{
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
final boolean durable = true;
channel.queueDeclare(QUEUE_NAME, durable, false, false, null);
System.out.println(channel.confirmSelect());
CountDownLatch latch = new CountDownLatch(10);
channel.addConfirmListener(new ConfirmListener()
{
@Override
public void handleAck(final long deliveryTag, final boolean multiple) throws IOException
{
System.out.println("Got ack " + deliveryTag);
latch.countDown();
}
@Override
public void handleNack(final long deliveryTag, final boolean multiple) throws IOException
{
System.out.println("Got no-ack " + deliveryTag);
latch.countDown();
}
});
channel.basicQos(1);
IntStream.rangeClosed(1,10).forEach(e -> {
try
{
String message = "Hello World! " + e;
channel.basicPublish("", QUEUE_NAME, null, message.getBytes("UTF-8"));
System.out.println(" [x] Sent '" + message + "'");
}
catch (IOException err)
{
err.printStackTrace();
}
});
latch.await(30, TimeUnit.SECONDS);
channel.close();
connection.close();
}
当在接收方时,我使用auto-ack或per message manual ack 我从ConfirmListener触发了几个handleAck。
[x] Sent 'Hello World! 1'
[x] Sent 'Hello World! 2'
[x] Sent 'Hello World! 3'
[x] Sent 'Hello World! 4'
[x] Sent 'Hello World! 5'
[x] Sent 'Hello World! 6'
[x] Sent 'Hello World! 7'
[x] Sent 'Hello World! 8'
Got ack 1
[x] Sent 'Hello World! 9'
[x] Sent 'Hello World! 10'
Got ack 6
Got ack 10
这可以实现每条消息的确认吗?
问候。