原文链接:https://www.rabbitmq.com/tutorials/tutorial-two-java.html

Work Queues

(using the Java Client)

In the first tutorial we wrote programs to send and receive messages from a named queue.In this one we'll create a Work Queue that will be used to distribute time-consuming tasks among multiple workers.

在上一篇教程中,我们写的程序从一个指定的队列发送和接收消息。本篇,我们将创建一个用于多个角色之间分配耗时的任务,工作队列(Work Queue)。


The main idea behind Work Queues(aka: Task Queues) is to avoid doing a resource-intensive task immediately and having to wait for it to complete. Instead we schedule the task to be done later. We encapsulate a task as a message and send it to a queue. A worker process running in the background will pop the tasks and eventually execute the job. When you run many workers the tasks will be shared between them.

工作队列(又名:任务队列)背后的主要思想是避免立即做一个资源密集型任务(一下子完成多个任务,即完成一个任务集),不必等待它完成。相反我们安排的每一个任务都将在稍后完成。一个在后台执行的worker进程将弹出任务,并最终执行任务。当你执行很多worker的任务时将在他们之间共享。


This concept is especially useful in web applications where it's impossible to handle a complex task during a short HTTP request window.

这一概念在web应用程序中是非常有用的,它不可能在很短的HTTP请求窗口处理一个复杂的任务。

Preparation

In the previous part of this tutorial we sent a message containing "Hello World!". Now we'll be sending strings that stand for complex tasks. We don't have a real-world task, like images to be resized or pdf files to be rendered, so let's fake it by just pretending we're busy - by using theThread.sleep() function. We'll take the number of dots in the string as its complexity; every dot will account for one second of "work". For example, a fake task described by Hello... will take three seconds.

在之前的教程中我们发送一个包含“Hello World!”的消息。现在我们将发送多个字符串来代表一个复杂的任务。我们没有一个现实的工作,比如图像的调整大小或者pdf文件的渲染,所以我们使当前线程睡眠(Thread.sleep())来假装我们很忙的样子。我们将把字符串中的点的数量作为它的复杂性,每一个点将占一秒钟的“工作”。比如说,一个假的任务是"Hello…"将需要三秒。


We will slightly modify the Send.java code from our previous example, to allow arbitrary messages to be sent from the command line. This program will schedule tasks to our work queue, so let's name it NewTask.java:

下面我们稍稍的修改一下之前例子中的Send.java的代码,允许任意的消息从命令行被发送出去。这个程序将为我们的任务安排工作队列,所以添加一个新类:NewTask.java:

String message = getMessage(argv);

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

Some help to get the message from the command line argument:

从命令行参数中获得一些帮助信息:

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

Our old Recv.java program also requires some changes: it needs to fake a second of work for every dot in the message body.It will handle delivered messages and perform the task, so let's call it Worker.java:

我们之前的那个Recv.java程序也需要一些修改:它需要假装的在消息体中每执行一个'.'就休息一秒钟。它将处理传递的信息并执行任务,所以就叫它Worker.java程序吧:

final Consumer consumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
String message = new String(body, "UTF-8"); System.out.println(" [x] Received '" + message + "'");
try {
doWork(message);
} finally {
System.out.println(" [x] Done");
}
}
};
boolean autoAck = true; // acknowledgment is covered below
channel.basicConsume(TASK_QUEUE_NAME, autoAck, consumer);

Our fake task to simulate execution time:

我们用一个假任务来模拟一段时间的执行:

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

Compile them as in tutorial one (with the jar files in the working directory):

下面来编译它们(和在工作目录中的这个jar文件):

$ javac -cp rabbitmq-client.jar NewTask.java Worker.java

RabbitMQ文档翻译——Work queues的更多相关文章

  1. (转)[Erlang 0080] RabbitMQ :VHost,Exchanges, Queues,Bindings and Channels

    和RabbitMQ这个项目的缘分好奇怪,很长一段时间内是只关注源代码,真的是Erlang开源项目中的典范;现在要在项目中应用RabbitMQ,从新的视角切入,全新的感觉.仿佛旧情人换了新衣,虽是熟稔却 ...

  2. RabbitMQ :VHost,Exchanges, Queues,Bindings and Channels

    和RabbitMQ这个项目的缘分好奇怪,很长一段时间内是只关注源代码,真的是Erlang开源项目中的典范;现在要在项目中应用RabbitMQ,从新的视角切入,全新的感觉.仿佛旧情人换了新衣,虽是熟稔却 ...

  3. Pythonpika PhpAmqpLib rabbitmq服务中queues被清空的异常处理 无模式数据库对数据结构的定义和控制

    /** * Declares queue, creates if needed * * @param string $queue * @param bool $passive * @param boo ...

  4. Rabbitmq(3) work queues

    轮询分发:每个消费者处理的消息是一样的 公平分发:能者多劳 *****公平分发 生产者 package com.aynu.bootamqp.service; import com.aynu.boota ...

  5. RabbitMQ文档翻译——Hello World!(下)

    Receiving That's it for our sender. Our receiver is pushed messages from RabbitMQ, so unlike the sen ...

  6. RabbitMQ文档翻译——Hello World!(上)

    文章主要翻译自RabbitMQ官方文档,主要是为了练习英语翻译,顺便学习一下RabbitMQ

  7. RabbitMQ(二) -- Work Queues

    RabbitMQ(一) -- Work Queues RabbitMQ使用Work Queues的主要目的是为了避免资源使用密集的任务,它不同于定时任务处理的方式,而是把任务封装为消息添加到队列中.而 ...

  8. [译]RabbitMQ教程C#版 - 工作队列

    先决条件 本教程假定RabbitMQ已经安装,并运行在localhost标准端口(5672).如果你使用不同的主机.端口或证书,则需要调整连接设置. 从哪里获得帮助 如果您在阅读本教程时遇到困难,可以 ...

  9. 译:3.RabbitMQ Java Client 之 Publish/Subscribe(发布和订阅)

    在上篇 RabbitMQ 之Work Queues (工作队列)教程中,我们创建了一个工作队列,工作队列背后的假设是每个任务都交付给一个工作者. 在这一部分,我们将做一些完全不同的事情 - 我们将向多 ...

随机推荐

  1. OpenCV 学习笔记 02 使用opencv处理图像

    1 不同色彩空间的转换 opencv 中有数百种关于不同色彩空间的转换方法,但常用的有三种色彩空间:灰度.BRG.HSV(Hue-Saturation-Value) 灰度 - 灰度色彩空间是通过去除彩 ...

  2. virtualbox主机与虚拟机互访,虚拟机上网

    实现virtualbox主机与虚拟机互访,同时虚拟机还可以上网: 主要通过配置两块网卡来实现: 1,先配置好一台虚拟机Slave1,这里使用CentOS : 2,使用VirtualBox复制这台虚拟机 ...

  3. [Android] 使用Include布局+Fragment滑动切换屏幕

        前面的文章已经讲述了"随手拍"项目图像处理的技术部分,该篇文章主要是主界面的布局及屏幕滑动切换,并结合鸿洋大神的视频和郭神的第一行代码(强推两人Android博客),完毕了 ...

  4. zookeeper注册中心安装(单机版)

    下载zookeeper-3.4.9.tar.gz wget http://apache.fayea.com/zookeeper/zookeeper-3.4.9/zookeeper-3.4.9.tar. ...

  5. 使用 Zipkin 和 Brave 实现分布式系统追踪(基础篇)

    一.Zipkin 1.1.简介 Zipkin 是一款开源的分布式实时数据追踪系统(Distributed Tracking System),基于 Google Dapper 的论文设计而来,由 Twi ...

  6. MySql(十八):MySql架构设计——高可用设计之 MySQL 监控

    前言: 一个经过高可用可扩展设计的 MySQL 数据库集群,如果没有一个足够精细足够强大的监控系统,同样可能会让之前在高可用设计方面所做的努力功亏一篑.一个系统,无论如何设计如何维护,都无法完全避免出 ...

  7. Android 设备管理API概览(Device Administration API)

    原文:http://android.eoe.cn/topic/android_sdk Android 2.2通过提供Android设备管理API的支持来引入企业应用支持.在系统级的设备管理API提供了 ...

  8. 利用阿里云如何开发一款直播app?

    在开发的过程中应该注意些什么?下面让小编告诉你: 随着互联网的发展,越来越多的人已经加入互联网的行列.而且很多的人也开始直播,和众多的网友分享自己身边事情.互联网还在加速发展,从PC互联网,到移动互联 ...

  9. Cocos2d-x 源代码分析 : Scheduler(定时器) 源代码分析

    源代码版本号 3.1r,转载请注明 我也最终不out了,開始看3.x的源代码了.此时此刻的心情仅仅能是wtf! !!!!!!! !.只是也最终告别CC时代了. cocos2d-x 源代码分析文件夹 h ...

  10. 浅析PCIe链路LTSSM状态机

    我们知道,在PCIe链路可以正常工作之前,需要对PCIe链路进行链路训练,在这个过程中,就会用LTSSM状态机.LTSSM全称是Link Training and Status State Machi ...