Java RabbitMQ 完整樣本 帶聯結斷開恢複,發布接收完整樣本
import java.io.IOException;import java.util.UUID;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.ScheduledExecutorService;import java.util.concurrent.TimeUnit;import java.util.concurrent.TimeoutException;import com.rabbitmq.client.Channel;import com.rabbitmq.client.Connection;import com.rabbitmq.client.ConnectionFactory;import com.rabbitmq.client.ConsumerCancelledException;import com.rabbitmq.client.QueueingConsumer;import com.rabbitmq.client.QueueingConsumer.Delivery;import com.rabbitmq.client.ShutdownSignalException;/* * @rabbitmq資料測試 * */public class RabbitMQTest {// 隊列名稱private final static String QUEUE_NAME = "hello";// 建立對像ConnectionFactory factory;// 聯結資訊Connection connection;// 頻道Channel channel = null;// 擷取資料隊列QueueingConsumer consumer = null;/** * InitMQ 初始化MQ資訊 * * * */public void InitMQ() {// 開啟串連和建立頻道,與發送端一樣factory = new ConnectionFactory();factory.setHost("192.168.2.110");factory.setUsername("rabbitmq");factory.setPassword("rabbitmq");factory.setVirtualHost("/");factory.setPort(5672);// 關鍵所在,指定線程池ExecutorService service = Executors.newFixedThreadPool(10);factory.setSharedExecutor(service);// 設定自動回復factory.setAutomaticRecoveryEnabled(true);factory.setNetworkRecoveryInterval(2);// 設定 沒10s ,重試一次factory.setTopologyRecoveryEnabled(false);// 設定不重新聲明交換器,隊列等資訊。try {connection = factory.newConnection();channel = connection.createChannel();// 聲明隊列,主要為了防止訊息接收者先運行此程式,隊列還不存在時建立隊列。channel.queueDeclare(QUEUE_NAME, false, false, false, null);System.out.println(" [*] Waiting for messages. To exit press CTRL+C");// 設定一條條的應答channel.basicQos(0, 1, false);// 建立隊列消費者consumer = new QueueingConsumer(channel);// 指定消費隊列 ,第二個參數false表示不自動應答channel.basicConsume(QUEUE_NAME, false, consumer);} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (TimeoutException e) {// TODO Auto-generated catch blocke.printStackTrace();}}/** * CycleSend 調用線程池迴圈發送資料<br/> * * * */public void CycleSend() {// 使用線程池ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);// 定時執行任務scheduledThreadPool.scheduleAtFixedRate(new Runnable() {@Overridepublic void run() {// 發送的訊息String message = "hello world!" + UUID.randomUUID();// TODO Auto-generated method stubtry {if (!channel.isOpen()) {// 初始化恢複// InitMQ();// System.out.println(" [x] 啟動發送重聯"+channel.isOpen());}if (channel.isOpen()) {channel.basicPublish("", QUEUE_NAME, null,message.getBytes());}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}, 1, 3, TimeUnit.SECONDS);}/** * ReceiveMQ 從MQ中收取資料 <br/> * 並且可以收穫MQ資訊資料 * * */public void ReceiveMQ() {Thread thr = new Thread(new Runnable() {@Overridepublic void run() {Cycle();}});thr.start();}// 是否斷開boolean isBroken = false;// 迴圈讀取資料protected void Cycle() {while (true) {// nextDelivery是一個阻塞方法(內部實現其實是阻塞隊列的take方法)QueueingConsumer.Delivery delivery;try {if (isBroken) {//channel.basicRecover();System.out.println(" [x] 開始接收資料可能會卡 ----"+ channel.isOpen());}if (channel.isOpen()) {delivery = consumer.nextDelivery();String message = new String(delivery.getBody());//應答channel.basicAck(delivery.getEnvelope().getDeliveryTag(),false);System.out.println(" [x] Received '" + message + "'");}} catch (ShutdownSignalException e) {try {if (channel.isOpen()) {// 異常情況恢複consumer = new QueueingConsumer(channel);channel.basicConsume(QUEUE_NAME, false, consumer);isBroken = false;System.out.println(" [x] 恢複成功 ----");}} catch (Exception e1) {isBroken = true;// TODO Auto-generated catch blocke1.printStackTrace();System.out.println(" [x] 接收線程--- ShutdownSignalException-Exception");}// TODO Auto-generated catch block// e.printStackTrace();} catch (ConsumerCancelledException e) {// TODO Auto-generated catch blocke.printStackTrace();System.out.println(" [x] 接收線程跳----ConsumerCancelledException");} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();System.out.println(" [x] 接收線程跳出 ----Exception");break;}}}}