RabbitMQ 持久化
阿新 • • 發佈:2019-01-05
如果RabbitMQ伺服器宕機,也會造成訊息丟失,可以使用訊息持久化和佇列持久化解決。佇列持久化需要生產者和消費者都開啟,訊息持久化在生產者開啟。
生產者:
package persist; import java.io.IOException; import java.util.concurrent.TimeoutException; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.MessageProperties; public class Send { private final static String QUEUE_NAME = "hello1"; public static void main(String[] args) throws IOException, TimeoutException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); //第二個引數true,開啟佇列持久化,false 關閉 channel.queueDeclare(QUEUE_NAME, true, false, false, null); String message = "Hello World 1111!"; //第三個引數開啟訊息持久化,null關閉 channel.basicPublish("", QUEUE_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes()); System.out.println(" [x] Sent '" + message + "'"); channel.close(); connection.close(); } }
消費者
package persist; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.QueueingConsumer; public class Reqv { private final static String QUEUE_NAME = "hello1"; public static void main(String[] argv) throws Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); //消費端也要佇列持久化,否則報錯 channel.queueDeclare(QUEUE_NAME, true, false, false, null); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); QueueingConsumer consumer = new QueueingConsumer(channel); //QueueingConsumer快取從伺服器發來的訊息 channel.basicConsume(QUEUE_NAME, true, consumer); while (true) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); //在另一個來自伺服器的訊息到來之前它會一直阻塞著 String message = new String(delivery.getBody()); System.out.println(" [x] Received '" + message + "'"); } } }