RabbitMQ 消息持久化、事务、Publisher的消息确认机制
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import com.rabbitmq.client.MessageProperties;
import com.rabbitmq.client.QueueingConsumer;
public class ConfirmDontLoseMessages {
private final static int msgCount = 10000; // 默认发送10000条消息
private final static String QUEUE_NAME = "confirm-test2"; // 队列名称
private static ConnectionFactory connectionFactory;
public static void main(String[] args)
throws IOException, InterruptedException {
connectionFactory = new ConnectionFactory();
connectionFactory.setHost("10.59.79.37");
connectionFactory.setUsername("admin");
connectionFactory.setPassword("admin");
connectionFactory.setPort(5672);
Thread consumerThread = new Thread(new Consumer());
Thread publisherThread = new Thread(new Publisher());
// 开启消费者线程
consumerThread.start();
// 开启生产者线程
publisherThread.start();
}
// 消息发布者
static class Publisher implements Runnable {
public void run() {
try {
long startTime = System.currentTimeMillis();
// 连接并非线程安全的,所以要每线程一个连接
Connection conn = connectionFactory.newConnection();
Channel ch = conn.createChannel();
// 创建一个持久化的,非独享,不自动删除的队列
ch.queueDeclare(QUEUE_NAME, true, false, false, null);
// 开启通道上的 publisher acknowledgements
ch.confirmSelect();
// 发送持久化消息,消息内容为helloWorld
for (long i = 0; i < msgCount; ++i) {
ch.basicPublish("", QUEUE_NAME,
MessageProperties.PERSISTENT_BASIC,
"helloWorld".getBytes());
}
// 等待所有消息都被ack或者nack,如果某个消息被nack,则抛出IOException
ch.waitForConfirmsOrDie();
long endTime = System.currentTimeMillis();
System.out.printf("Test took %.3fs\n", (float) (endTime - startTime) / 1000);
// 删除队列,不论是否在使用中
ch.queueDelete(QUEUE_NAME);
ch.close();
conn.close();
} catch (Throwable e) {
System.out.println("damn fuck! error detected :(");
System.out.print(e);
}
}
}
// 消息消费者
static class Consumer implements Runnable {
public void run() {
try {
// 每线程一个连接
Connection conn = connectionFactory.newConnection();
Channel ch = conn.createChannel();
ch.queueDeclare(QUEUE_NAME, true, false, false, null);
// 创建消息消费者
QueueingConsumer qc = new QueueingConsumer(ch);
ch.basicConsume(QUEUE_NAME, true, qc);
for (int i = 0; i < msgCount; ++i) {
qc.nextDelivery();
}
// 关闭通道和连接
System.out.println("consumer done");
ch.close();
conn.close();
} catch (Throwable e) {
System.out.println("damn fuck! some error happened!");
System.out.print(e);
}
}
}
}
/** Wait until all messages published since the last call have
* been either ack'd or nack'd by the broker. If any of the
* messages were nack'd, waitForConfirmsOrDie will throw an
* IOException. When called on a non-Confirm channel, it will
* throw an IllegalStateException.
* @throws java.lang.IllegalStateException
*/
void waitForConfirmsOrDie() throws IOException, InterruptedException;