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);
        }
    }

}


  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值