RabbitMQ 消息輪詢和消息確認機制

轉載出處:http://blog.csdn.net/liangwenmail/article/details/60877179

1 消息輪詢:默認的情況下,服務器會將消息發送給下一個消費者,使得每個消費者獲得消息數量儘量相同。

2 消息確認機制:默認手動確認,需要消費者反饋給服務器一個確認信號,告知服務器可以在消息隊列中刪除消息,如果服務器未收到確認信號若消費者斷開鏈接,將會把消息發送給下一個消費者,使得消息不會丟失。自動確認,服務器端會在消費者取得消息後在隊列中刪除消息,若此時消費者未處理完消息宕掉了,消息會丟失。如果手動確認忘記反饋確認信號,則消息在服務器佔用的內存越來越多,應該記得反饋確認信號給服務器;


生產者:

  1. package queue;  
  2.   
  3. import java.io.IOException;  
  4. import java.util.concurrent.TimeoutException;  
  5.   
  6. import com.rabbitmq.client.Channel;  
  7. import com.rabbitmq.client.Connection;  
  8. import com.rabbitmq.client.ConnectionFactory;  
  9.   
  10. public class SendNewTask {  
  11.     private final static String QUEUE_NAME = “newTask”;  
  12.     public static void main(String[] args) throws IOException, TimeoutException {  
  13.         ConnectionFactory factory = new ConnectionFactory();  
  14.         factory.setHost(”localhost”);  
  15.         Connection connection = factory.newConnection();  
  16.         Channel channel = connection.createChannel();  
  17.           
  18.         channel.queueDeclare(QUEUE_NAME, falsefalsefalsenull);  
  19.           
  20.         String[] msg={”hello…word…”,“hash…map…”};  
  21.         String message = getMessage(msg);  
  22.           
  23.         channel.basicPublish(”“, QUEUE_NAME, null, message.getBytes());  
  24.         System.out.println(”[x] Sent ’” + message + “’”);  
  25.           
  26.         channel.close();  
  27.         connection.close();  
  28.           
  29.     }  
  30.       
  31.     private static String getMessage(String[] strings){  
  32.         if (strings.length < 1)  
  33.             return “Hello World!”;  
  34.         return joinStrings(strings, “ ”);  
  35.     }  
  36.   
  37.     private static String joinStrings(String[] strings, String delimiter) {  
  38.         int length = strings.length;  
  39.         if (length == 0return “”;  
  40.         StringBuilder words = new StringBuilder(strings[0]);  
  41.         for (int i = 1; i < length; i++) {  
  42.             words.append(delimiter).append(strings[i]);  
  43.         }  
  44.         return words.toString();  
  45.     }  
  46. }  
package queue;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

public class SendNewTask {
    private final static String QUEUE_NAME = "newTask";
    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.queueDeclare(QUEUE_NAME, false, false, false, null);

        String[] msg={"hello...word...","hash...map..."};
        String message = getMessage(msg);

        channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
        System.out.println("[x] Sent '" + message + "'");

        channel.close();
        connection.close();

    }

    private static String getMessage(String[] strings){
        if (strings.length < 1)
            return "Hello World!";
        return joinStrings(strings, " ");
    }

    private static String joinStrings(String[] strings, String delimiter) {
        int length = strings.length;
        if (length == 0) return "";
        StringBuilder words = new StringBuilder(strings[0]);
        for (int i = 1; i < length; i++) {
            words.append(delimiter).append(strings[i]);
        }
        return words.toString();
    }
}

消費者 1

  1. package queue;  
  2.   
  3. import java.io.IOException;  
  4. import java.util.Calendar;  
  5.   
  6. import com.rabbitmq.client.Channel;  
  7. import com.rabbitmq.client.Connection;  
  8. import com.rabbitmq.client.ConnectionFactory;  
  9. import com.rabbitmq.client.ConsumerCancelledException;  
  10. import com.rabbitmq.client.QueueingConsumer;  
  11. import com.rabbitmq.client.ShutdownSignalException;  
  12.   
  13. public class ReqvWork {  
  14.     private final static String QUEUE_NAME = “newTask”;  
  15.       
  16.     public static void main(String[] args) throws IOException, ShutdownSignalException, ConsumerCancelledException, InterruptedException {  
  17.         ConnectionFactory factory = new ConnectionFactory();  
  18.         factory.setHost(”localhost”);  
  19.         Connection connection = factory.newConnection();  
  20.         Channel channel = connection.createChannel();  
  21.           
  22.         channel.queueDeclare(QUEUE_NAME, falsefalsefalsenull);  
  23.         System.out.println(” [*] Waiting for messages. To exit press CTRL+C”);  
  24.           
  25.         QueueingConsumer consumer = new QueueingConsumer(channel); //QueueingConsumer緩存從服務器發來的消息  
  26.           
  27.         //第二個參數true,自動確認機制,如果消息消費者和服務器斷開鏈接會丟失消息;false 關閉自動確認機制,手動確認  
  28.         channel.basicConsume(QUEUE_NAME, false, consumer);   
  29.           
  30.         while (true) {  
  31.             QueueingConsumer.Delivery delivery = consumer.nextDelivery(); //在另一個來自服務器的消息到來之前它會一直阻塞着  
  32.             String message = new String(delivery.getBody());  
  33.             doWork(message);  
  34.             System.out.println(” [x] Received ’” + message + “’”);  
  35.             System.out.println(” [x] done”);  
  36.               
  37.             channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); //手動消息確認,反饋確認信息  
  38.         }  
  39.   
  40.     }  
  41.       
  42.     private static void doWork(String task) throws InterruptedException {  
  43.         for (char ch: task.toCharArray()) {  
  44.             if (ch == ‘.’) Thread.sleep(1000);  
  45.         }  
  46.     }  
  47.   
  48. }  
package queue;

import java.io.IOException;
import java.util.Calendar;

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.ShutdownSignalException;

public class ReqvWork {
    private final static String QUEUE_NAME = "newTask";

    public static void main(String[] args) throws IOException, ShutdownSignalException, ConsumerCancelledException, InterruptedException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

        QueueingConsumer consumer = new QueueingConsumer(channel); //QueueingConsumer緩存從服務器發來的消息

        //第二個參數true,自動確認機制,如果消息消費者和服務器斷開鏈接會丟失消息;false 關閉自動確認機制,手動確認
        channel.basicConsume(QUEUE_NAME, false, consumer); 

        while (true) {
            QueueingConsumer.Delivery delivery = consumer.nextDelivery(); //在另一個來自服務器的消息到來之前它會一直阻塞着
            String message = new String(delivery.getBody());
            doWork(message);
            System.out.println(" [x] Received '" + message + "'");
            System.out.println(" [x] done");

            channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); //手動消息確認,反饋確認信息
        }

    }

    private static void doWork(String task) throws InterruptedException {
        for (char ch: task.toCharArray()) {
            if (ch == '.') Thread.sleep(1000);
        }
    }

}

消費者2

  1. package queue;  
  2.   
  3. import java.io.IOException;  
  4. import java.util.Calendar;  
  5.   
  6. import com.rabbitmq.client.Channel;  
  7. import com.rabbitmq.client.Connection;  
  8. import com.rabbitmq.client.ConnectionFactory;  
  9. import com.rabbitmq.client.ConsumerCancelledException;  
  10. import com.rabbitmq.client.QueueingConsumer;  
  11. import com.rabbitmq.client.ShutdownSignalException;  
  12.   
  13. public class ReqvWork1 {  
  14.     private final static String QUEUE_NAME = “newTask”;  
  15.       
  16.     public static void main(String[] args) throws IOException, ShutdownSignalException, ConsumerCancelledException, InterruptedException {  
  17.         ConnectionFactory factory = new ConnectionFactory();  
  18.         factory.setHost(”localhost”);  
  19.         Connection connection = factory.newConnection();  
  20.         Channel channel = connection.createChannel();  
  21.           
  22.         channel.queueDeclare(QUEUE_NAME, falsefalsefalsenull);  
  23.         System.out.println(” [*] Waiting for messages. To exit press CTRL+C”);  
  24.           
  25.         QueueingConsumer consumer = new QueueingConsumer(channel); //QueueingConsumer緩存從服務器發來的消息  
  26.           
  27.         //第二個參數true,自動確認機制,如果消息消費者和服務器斷開鏈接會丟失消息;false 關閉自動確認機制,手動確認  
  28.         channel.basicConsume(QUEUE_NAME, false, consumer);   
  29.           
  30.         while (true) {  
  31.             QueueingConsumer.Delivery delivery = consumer.nextDelivery(); //在另一個來自服務器的消息到來之前它會一直阻塞着  
  32.             String message = new String(delivery.getBody());  
  33.             doWork(message);  
  34.             System.out.println(” [x1] Received ’” + message + “’”);  
  35.             System.out.println(” [x1] done”);  
  36.               
  37.             channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); //手動消息確認  
  38.         }  
  39.   
  40.     }  
  41.       
  42.     private static void doWork(String task) throws InterruptedException {  
  43.         for (char ch: task.toCharArray()) {  
  44.             if (ch == ‘.’) Thread.sleep(1000);  
  45.         }  
  46.     }  
  47.   
  48. }  
package queue;

import java.io.IOException;
import java.util.Calendar;

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.ShutdownSignalException;

public class ReqvWork1 {
    private final static String QUEUE_NAME = "newTask";

    public static void main(String[] args) throws IOException, ShutdownSignalException, ConsumerCancelledException, InterruptedException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

        QueueingConsumer consumer = new QueueingConsumer(channel); //QueueingConsumer緩存從服務器發來的消息

        //第二個參數true,自動確認機制,如果消息消費者和服務器斷開鏈接會丟失消息;false 關閉自動確認機制,手動確認
        channel.basicConsume(QUEUE_NAME, false, consumer); 

        while (true) {
            QueueingConsumer.Delivery delivery = consumer.nextDelivery(); //在另一個來自服務器的消息到來之前它會一直阻塞着
            String message = new String(delivery.getBody());
            doWork(message);
            System.out.println(" [x1] Received '" + message + "'");
            System.out.println(" [x1] done");

            channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); //手動消息確認
        }

    }

    private static void doWork(String task) throws InterruptedException {
        for (char ch: task.toCharArray()) {
            if (ch == '.') Thread.sleep(1000);
        }
    }

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章