RabbitMQ (二)工做队列

转载请标明出处:http://blog.csdn.net/lmj623565791/article/details/37620057 java

本系列教程主要来自于官网入门教程的翻译,而后本身进行了部分的修改与实验,内容仅供参考。 web

上一篇博客中咱们写了经过一个命名的队列发送和接收消息,若是你还不了解请点击:RabbitMQ 入门 Helloworld。这篇中咱们将会建立一个工做队列用来在工做者(consumer)间分发耗时任务。 学习

工做队列的主要任务是:避免马上执行资源密集型任务,而后必须等待其完成。相反地,咱们进行任务调度:咱们把任务封装为消息发送给队列。工做进行在后台运行并不断的从队列中取出任务而后执行。当你运行了多个工做进程时,任务队列中的任务将会被工做进程共享执行。
这样的概念在web应用中极其有用,当在很短的HTTP请求间须要执行复杂的任务。
一、 准备

咱们使用Thread.sleep来模拟耗时的任务。咱们在发送到队列的消息的末尾添加必定数量的点,每一个点表明在工做线程中须要耗时1秒,例如hello…将会须要等待3秒。 测试

发送端: fetch

NewTask.java spa

[java]  view plain  copy
  1. package com.zhy.rabbit._02_workqueue;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. import com.rabbitmq.client.Channel;  
  6. import com.rabbitmq.client.Connection;  
  7. import com.rabbitmq.client.ConnectionFactory;  
  8.   
  9. public class NewTask  
  10. {  
  11.     //队列名称  
  12.     private final static String QUEUE_NAME = "workqueue";  
  13.   
  14.     public static void main(String[] args) throws IOException  
  15.     {  
  16.         //建立链接和频道  
  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.         //发送10条消息,依次在消息后面附加1-10个点  
  24.         for (int i = 0; i < 10; i++)  
  25.         {  
  26.             String dots = "";  
  27.             for (int j = 0; j <= i; j++)  
  28.             {  
  29.                 dots += ".";  
  30.             }  
  31.             String message = "helloworld" + dots+dots.length();  
  32.             channel.basicPublish("", QUEUE_NAME, null, message.getBytes());  
  33.             System.out.println(" [x] Sent '" + message + "'");  
  34.         }  
  35.         //关闭频道和资源  
  36.         channel.close();  
  37.         connection.close();  
  38.   
  39.     }  
  40.   
  41.   
  42. }  

接收端: .net

Work.java 线程

[java]  view plain  copy
  1. package com.zhy.rabbit._02_workqueue;  
  2.   
  3. import com.rabbitmq.client.Channel;  
  4. import com.rabbitmq.client.Connection;  
  5. import com.rabbitmq.client.ConnectionFactory;  
  6. import com.rabbitmq.client.QueueingConsumer;  
  7.   
  8. public class Work  
  9. {  
  10.     //队列名称  
  11.     private final static String QUEUE_NAME = "workqueue";  
  12.   
  13.     public static void main(String[] argv) throws java.io.IOException,  
  14.             java.lang.InterruptedException  
  15.     {  
  16.         //区分不一样工做进程的输出  
  17.         int hashCode = Work.class.hashCode();  
  18.         //建立链接和频道  
  19.         ConnectionFactory factory = new ConnectionFactory();  
  20.         factory.setHost("localhost");  
  21.         Connection connection = factory.newConnection();  
  22.         Channel channel = connection.createChannel();  
  23.         //声明队列  
  24.         channel.queueDeclare(QUEUE_NAME, falsefalsefalsenull);  
  25.         System.out.println(hashCode  
  26.                 + " [*] Waiting for messages. To exit press CTRL+C");  
  27.       
  28.         QueueingConsumer consumer = new QueueingConsumer(channel);  
  29.         // 指定消费队列  
  30.         channel.basicConsume(QUEUE_NAME, true, consumer);  
  31.         while (true)  
  32.         {  
  33.             QueueingConsumer.Delivery delivery = consumer.nextDelivery();  
  34.             String message = new String(delivery.getBody());  
  35.   
  36.             System.out.println(hashCode + " [x] Received '" + message + "'");  
  37.             doWork(message);  
  38.             System.out.println(hashCode + " [x] Done");  
  39.   
  40.         }  
  41.   
  42.     }  
  43.   
  44.     /** 
  45.      * 每一个点耗时1s 
  46.      * @param task 
  47.      * @throws InterruptedException 
  48.      */  
  49.     private static void doWork(String task) throws InterruptedException  
  50.     {  
  51.         for (char ch : task.toCharArray())  
  52.         {  
  53.             if (ch == '.')  
  54.                 Thread.sleep(1000);  
  55.         }  
  56.     }  
  57. }  

Round-robin 转发
使用任务队列的好处是可以很容易的并行工做。若是咱们积压了不少工做,咱们仅仅经过增长更多的工做者就能够解决问题,使系统的伸缩性更加容易。
下面咱们先运行3个工做者(Work.java)实例,而后运行NewTask.java,3个工做者实例都会获得信息。可是如何分配呢?让咱们来看输出结果:[x] Sent 'helloworld.1'
[x] Sent 'helloworld..2'
[x] Sent 'helloworld...3'
[x] Sent 'helloworld....4'
[x] Sent 'helloworld.....5'
[x] Sent 'helloworld......6'
[x] Sent 'helloworld.......7'
[x] Sent 'helloworld........8'
[x] Sent 'helloworld.........9'
[x] Sent 'helloworld..........10'

工做者1:
605645 [*] Waiting for messages. To exit press CTRL+C
605645 [x] Received 'helloworld.1'
605645 [x] Done
605645 [x] Received 'helloworld....4'
605645 [x] Done
605645 [x] Received 'helloworld.......7'
605645 [x] Done
605645 [x] Received 'helloworld..........10'
605645 [x] Done 翻译

工做者2:
18019860 [*] Waiting for messages. To exit press CTRL+C
18019860 [x] Received 'helloworld..2'
18019860 [x] Done
18019860 [x] Received 'helloworld.....5'
18019860 [x] Done
18019860 [x] Received 'helloworld........8'
18019860 [x] Done blog

工做者3:
18019860 [*] Waiting for messages. To exit press CTRL+C
18019860 [x] Received 'helloworld...3'
18019860 [x] Done
18019860 [x] Received 'helloworld......6'
18019860 [x] Done
18019860 [x] Received 'helloworld.........9'
18019860 [x] Done
能够看到,默认的,RabbitMQ会一个一个的发送信息给下一个消费者(consumer),而不考虑每一个任务的时长等等,且是一次性分配,并不是一个一个分配。平均的每一个消费者将会得到相等数量的消息。这样分发消息的方式叫作round-robin。

二、 消息应(message acknowledgments)
执行一个任务须要花费几秒钟。你可能会担忧当一个工做者在执行任务时发生中断。咱们上面的代码,一旦RabbItMQ交付了一个信息给消费者,会立刻从内存中移除这个信息。在这种状况下,若是杀死正在执行任务的某个工做者,咱们会丢失它正在处理的信息。咱们也会丢失已经转发给这个工做者且它还未执行的消息。
上面的例子,咱们首先开启两个任务,而后执行发送任务的代码(NewTask.java),而后当即关闭第二个任务,结果为:
工做者2:

31054905 [*] Waiting for messages. To exit press CTRL+C
31054905 [x] Received 'helloworld..2'
31054905 [x] Done
31054905 [x] Received 'helloworld....4'

工做者1:
18019860 [*] Waiting for messages. To exit press CTRL+C
18019860 [x] Received 'helloworld.1'
18019860 [x] Done
18019860 [x] Received 'helloworld...3'
18019860 [x] Done
18019860 [x] Received 'helloworld.....5'
18019860 [x] Done
18019860 [x] Received 'helloworld.......7'
18019860 [x] Done
18019860 [x] Received 'helloworld.........9'
18019860 [x] Done
能够看到,第二个工做者至少丢失了6,8,10号任务,且4号任务未完成。

可是,咱们不但愿丢失任何任务(信息)。当某个工做者(接收者)被杀死时,咱们但愿将任务传递给另外一个工做者。
为了保证消息永远不会丢失,RabbitMQ支持消息应答(message acknowledgments)。消费者发送应答给RabbitMQ,告诉它信息已经被接收和处理,而后RabbitMQ能够自由的进行信息删除。
若是消费者被杀死而没有发送应答,RabbitMQ会认为该信息没有被彻底的处理,而后将会从新转发给别的消费者。经过这种方式,你能够确认信息不会被丢失,即便消者偶尔被杀死。
这种机制并无超时时间这么一说,RabbitMQ只有在消费者链接断开是从新转发此信息。若是消费者处理一个信息须要耗费特别特别长的时间是容许的。
消息应答默认是打开的。上面的代码中咱们经过显示的设置autoAsk=true关闭了这种机制。下面咱们修改代码(Work.java):

[java]  view plain  copy
  1. boolean ack = false ; //打开应答机制  
  2. channel.basicConsume(QUEUE_NAME, ack, consumer);  
  3. //另外须要在每次处理完成一个消息后,手动发送一次应答。  
  4. channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);  

完整修改后的Work.java

[java]  view plain  copy
  1. package com.zhy.rabbit._02_workqueue.ack;  
  2.   
  3. import com.rabbitmq.client.Channel;  
  4. import com.rabbitmq.client.Connection;  
  5. import com.rabbitmq.client.ConnectionFactory;  
  6. import com.rabbitmq.client.QueueingConsumer;  
  7.   
  8. public class Work  
  9. {  
  10.     //队列名称  
  11.     private final static String QUEUE_NAME = "workqueue";  
  12.   
  13.     public static void main(String[] argv) throws java.io.IOException,  
  14.             java.lang.InterruptedException  
  15.     {  
  16.         //区分不一样工做进程的输出  
  17.         int hashCode = Work.class.hashCode();  
  18.         //建立链接和频道  
  19.         ConnectionFactory factory = new ConnectionFactory();  
  20.         factory.setHost("localhost");  
  21.         Connection connection = factory.newConnection();  
  22.         Channel channel = connection.createChannel();  
  23.         //声明队列  
  24.         channel.queueDeclare(QUEUE_NAME, falsefalsefalsenull);  
  25.         System.out.println(hashCode  
  26.                 + " [*] Waiting for messages. To exit press CTRL+C");  
  27.         QueueingConsumer consumer = new QueueingConsumer(channel);  
  28.         // 指定消费队列  
  29.         boolean ack = false ; //打开应答机制  
  30.         channel.basicConsume(QUEUE_NAME, ack, consumer);  
  31.         while (true)  
  32.         {  
  33.             QueueingConsumer.Delivery delivery = consumer.nextDelivery();  
  34.             String message = new String(delivery.getBody());  
  35.   
  36.             System.out.println(hashCode + " [x] Received '" + message + "'");  
  37.             doWork(message);  
  38.             System.out.println(hashCode + " [x] Done");  
  39.             //发送应答  
  40.             channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);  
  41.   
  42.         }  
  43.   
  44.     }  
  45. }  
测试:
咱们把消息数量改成5,而后先打开两个消费者(Work.java),而后发送任务(NewTask.java),当即关闭一个消费者,观察输出:
[x] Sent 'helloworld.1'
[x] Sent 'helloworld..2'
[x] Sent 'helloworld...3'
[x] Sent 'helloworld....4'
[x] Sent 'helloworld.....5'

工做者2
18019860 [*] Waiting for messages. To exit press CTRL+C
18019860 [x] Received 'helloworld..2'
18019860 [x] Done
18019860 [x] Received 'helloworld....4'

工做者1
31054905 [*] Waiting for messages. To exit press CTRL+C
31054905 [x] Received 'helloworld.1'
31054905 [x] Done
31054905 [x] Received 'helloworld...3'
31054905 [x] Done
31054905 [x] Received 'helloworld.....5'
31054905 [x] Done
31054905 [x] Received 'helloworld....4'
31054905 [x] Done

能够看到工做者2没有完成的任务4,从新转发给工做者1进行完成了。

三、 消息持久化(Message durability)

咱们已经学习了即便消费者被杀死,消息也不会被丢失。可是若是此时RabbitMQ服务被中止,咱们的消息仍然会丢失。

当RabbitMQ退出或者异常退出,将会丢失全部的队列和信息,除非你告诉它不要丢失。咱们须要作两件事来确保信息不会被丢失:咱们须要给全部的队列和消息设置持久化的标志。
第一, 咱们须要确认RabbitMQ永远不会丢失咱们的队列。为了这样,咱们须要声明它为持久化的。
boolean durable = true;
channel.queueDeclare("task_queue", durable, false, false, null);
注:RabbitMQ不容许使用不一样的参数从新定义一个队列,因此已经存在的队列,咱们没法修改其属性。
第二, 咱们须要标识咱们的信息为持久化的。经过设置MessageProperties(implements BasicProperties)值为PERSISTENT_TEXT_PLAIN。
channel.basicPublish("", "task_queue",MessageProperties.PERSISTENT_TEXT_PLAIN,message.getBytes());
如今你能够执行一个发送消息的程序,而后关闭服务,再从新启动服务,运行消费者程序作下实验。

四、公平转发(Fair dispatch)
或许会发现,目前的消息转发机制(Round-robin)并不是是咱们想要的。例如,这样一种状况,对于两个消费者,有一系列的任务,奇数任务特别耗时,而偶数任务却很轻松,这样形成一个消费者一直繁忙,另外一个消费者却很快执行完任务后等待。
形成这样的缘由是由于RabbitMQ仅仅是当消息到达队列进行转发消息。并不在意有多少任务消费者并未传递一个应答给RabbitMQ。仅仅盲目转发全部的奇数给一个消费者,偶数给另外一个消费者。
为了解决这样的问题,咱们可使用basicQos方法,传递参数为prefetchCount = 1。这样告诉RabbitMQ不要在同一时间给一个消费者超过一条消息。换句话说,只有在消费者空闲的时候会发送下一条信息。
[java]  view plain  copy
  1. int prefetchCount = 1;  
  2. channel.basicQos(prefetchCount);  
注:若是全部的工做者都处于繁忙状态,你的队列有可能被填充满。你可能会观察队列的使用状况,而后增长工做者,或者使用别的什么策略。
测试:改变发送消息的代码,将消息末尾点数改成6-2个,而后首先开启两个工做者,接着发送消息:

[x] Sent 'helloworld......6'
[x] Sent 'helloworld.....5'
[x] Sent 'helloworld....4'
[x] Sent 'helloworld...3'
[x] Sent 'helloworld..2'

工做者1:
18019860 [*] Waiting for messages. To exit press CTRL+C
18019860 [x] Received 'helloworld......6'
18019860 [x] Done
18019860 [x] Received 'helloworld...3'
18019860 [x] Done

工做者2:
31054905 [*] Waiting for messages. To exit press CTRL+C
31054905 [x] Received 'helloworld.....5'
31054905 [x] Done
31054905 [x] Received 'helloworld....4'
31054905 [x] Done
31054905 [x] Received 'helloworld..2'
31054905 [x] Done

能够看出此时并无照以前的Round-robin机制进行转发消息,而是当消费者不忙时进行转发。且这种模式下支持动态增长消费者,由于消息并无发送出去,动态增长了消费者立刻投入工做。而默认的转发机制会形成,即便动态增长了消费者,此时的消息已经分配完毕,没法当即加入工做,即便有不少未完成的任务。


五、完整的代码

NewTask.java

[java]  view plain  copy
  1. package com.zhy.rabbit._02_workqueue.ackandpersistence;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. import com.rabbitmq.client.Channel;  
  6. import com.rabbitmq.client.Connection;  
  7. import com.rabbitmq.client.ConnectionFactory;  
  8. import com.rabbitmq.client.MessageProperties;  
  9.   
  10. public class NewTask  
  11. {  
  12.     // 队列名称  
  13.     private final static String QUEUE_NAME = "workqueue_persistence";  
  14.   
  15.     public static void main(String[] args) throws IOException  
  16.     {  
  17.         // 建立链接和频道  
  18.         ConnectionFactory factory = new ConnectionFactory();  
  19.         factory.setHost("localhost");  
  20.         Connection connection = factory.newConnection();  
  21.         Channel channel = connection.createChannel();  
  22.         // 声明队列  
  23.         boolean durable = true;// 一、设置队列持久化  
  24.         channel.queueDeclare(QUEUE_NAME, durable, falsefalsenull);  
  25.         // 发送10条消息,依次在消息后面附加1-10个点  
  26.         for (int i = 5; i > 0; i--)  
  27.         {  
  28.             String dots = "";  
  29.             for (int j = 0; j <= i; j++)  
  30.             {  
  31.                 dots += ".";  
  32.             }  
  33.             String message = "helloworld" + dots + dots.length();  
  34.             // MessageProperties 二、设置消息持久化  
  35.             channel.basicPublish("", QUEUE_NAME,  
  36.                     MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes());  
  37.             System.out.println(" [x] Sent '" + message + "'");  
  38.         }  
  39.         // 关闭频道和资源  
  40.         channel.close();  
  41.         connection.close();  
  42.   
  43.     }  
  44.   
  45. }  

Work.java
[java]  view plain  copy
  1. package com.zhy.rabbit._02_workqueue.ackandpersistence;  
  2.   
  3. import com.rabbitmq.client.Channel;  
  4. import com.rabbitmq.client.Connection;  
  5. import com.rabbitmq.client.ConnectionFactory;  
  6. import com.rabbitmq.client.QueueingConsumer;  
  7.   
  8. public class Work  
  9. {  
  10.     // 队列名称  
  11.     private final static String QUEUE_NAME = "workqueue_persistence";  
  12.   
  13.     public static void main(String[] argv) throws java.io.IOException,  
  14.             java.lang.InterruptedException  
  15.     {  
  16.         // 区分不一样工做进程的输出  
  17.         int hashCode = Work.class.hashCode();  
  18.         // 建立链接和频道  
  19.         ConnectionFactory factory = new ConnectionFactory();  
  20.         factory.setHost("localhost");  
  21.         Connection connection = factory.newConnection();  
  22.         Channel channel = connection.createChannel();  
  23.         // 声明队列  
  24.         boolean durable = true;  
  25.         channel.queueDeclare(QUEUE_NAME, durable, falsefalsenull);  
  26.         System.out.println(hashCode  
  27.                 + " [*] Waiting for messages. To exit press CTRL+C");  
  28.         //设置最大服务转发消息数量  
  29.         int prefetchCount = 1;  
  30.         channel.basicQos(prefetchCount);  
  31.         QueueingConsumer consumer = new QueueingConsumer(channel);  
  32.         // 指定消费队列  
  33.         boolean ack = false// 打开应答机制  
  34.         channel.basicConsume(QUEUE_NAME, ack, consumer);  
  35.         while (true)  
  36.         {  
  37.             QueueingConsumer.Delivery delivery = consumer.nextDelivery();  
  38.             String message = new String(delivery.getBody());  
  39.   
  40.             System.out.println(hashCode + " [x] Received '" + message + "'");  
  41.             doWork(message);  
  42.             System.out.println(hashCode + " [x] Done");  
  43.             //channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);  
  44.             channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);  
  45.   
  46.         }  
  47.   
  48.     }  
  49.   
  50.     /** 
  51.      * 每一个点耗时1s 
  52.      *  
  53.      * @param task 
  54.      * @throws InterruptedException 
  55.      */  
  56.     private static void doWork(String task) throws InterruptedException  
  57.     {  
  58.         for (char ch : task.toCharArray())  
  59.         {  
  60.             if (ch == '.')  
  61.                 Thread.sleep(1000);  
  62.         }  
  63.     }  
  64. }  
相关文章
相关标签/搜索