RabbitMQ官方文档翻译之Routing(四)

Routing  路由模式   (using the Java client)

In the previous tutorial we built a simple logging system. We were able to broadcast log messages to many receivers.

在上一篇教程中,我们构造了一个简单的日志系统。我们可以用fanout exchange 广播日志消息给所有的receivers

In this tutorial we're going to add a feature to it - we're going to make it possible to subscribe only to a subset of the messages. For example, we will be able to direct only critical error messages to the log file (to save disk space), while still being able to print all of the log messages on the console.

在本教程中,我们将为其添加一个功能 - consumer仅订阅消息的一部分,而不像上一篇教程中每个consumer会订阅RabbitMQ中所有的消息。 例如,我们将仅将关键的错误消息引导到日志文件(以节省磁盘空间),同时仍然能够在控制台上打印所有日志消息。

Bindings

In previous examples we were already creating bindings. You may recall code like:

在上一篇教程中,我们仅仅是将exchange和queue绑定在一起,并没有指定routing key

channel.queueBind(queueName, EXCHANGE_NAME, "");

A binding is a relationship between an exchange and a queue. This can be simply read as: the queue is interested in messages from this exchange.

绑定代表exchange和queue建立关系。 可以简单的理解为:队列想要订阅来自此exchange的消息

Bindings can take an extra routingKey parameter. To avoid the confusion with a basic_publishparameter we're going to call it a binding key. This is how we could create a binding with a key:

实际上,在绑定时可以带具体的routingKey 参数。上一篇教程因为我们用的是fanout类型的exchange,这个模式下routingKey被忽略,所以routingKey为空字符串。

其实这个参数的名称和basicPublish()的参数名是相同了。为了避免混淆,我们把它叫做binding key。

 Queue.BindOk queueBind(String queue, String exchange, String routingKey=>bindingKey) throws IOException;


 void basicPublish(String exchange, String routingKey, BasicProperties props, byte[] body) throws IOException;


绑定一个队列到exchange,binding key是black

channel.queueBind(queueName, EXCHANGE_NAME, "black");

The meaning of a binding key depends on the exchange type. The fanout exchanges, which we used previously, simply ignored its value.

对于fanout的exchange来说,这个参数是被忽略的。所以空字符串代替

Direct exchange

Our logging system from the previous tutorial broadcasts all messages to all consumers. We want to extend that to allow filtering messages based on their severity. For example we may want a program which writes log messages to the disk to only receive critical errors, and not waste disk space on warning or info log messages.

在上一个教程中日志记录系统会向所有消费者广播所有消息。现在我们希望将其扩展为消费者可以根据日志的级别进行过滤。 例如,我们可能仅仅是将Error级别的日志写入磁盘,而不会浪费warning或info级别的日志不做存储,以节省磁盘空间。

We were using a fanout exchange, which doesn't give us much flexibility - it's only capable of mindless broadcasting.

因此我们不能再使用fanout exchange,它不太灵活 - 只能无脑地广播所有消息给所有的消费者。

We will use a direct exchange instead. The routing algorithm behind a direct exchange is simple - a message goes to the queues whose binding key exactly matches the routing key of the message.

direct exchange能达到我们的目的。 direct exchange背后的路由算法其实很简单 - 消息会传递到bindingkey与消息携带的routingKey完全匹配的队列。

To illustrate that, consider the following setup:

In this setup, we can see the direct exchange X with two queues bound to it. The first queue is bound with binding key orange, and the second has two bindings, one with binding key black and the other one with green.

我们可以看到这个direct exchange X和两个队列绑定了。第一个队列Q1的binding key是orange,第二个队列的bingkey是black,green

In such a setup a message published to the exchange with a routing key orange will be routed to queue Q1. Messages with a routing key of black or green will Go to Q2. All other messages will be discarded.

如图,如果一个消息发布到exchange并且具有routingkey是orange,那消息将被路由到Q1队列。如果消息具有一个black或green的routing key将被路由到Q2。如果routing key不能够匹配到,消息将会丢弃。

Multiple bindings

It is perfectly legal to bind multiple queues with the same binding key. In our example we could add a binding between X and Q1 with binding key black. In that case, the direct exchange will behave like fanout and will broadcast the message to all the matching queues. A message with routing key black will be delivered to both Q1 and Q2.

使用相同的bindKey绑定多个队列是合法的。 在我们的示例中,我们添加一个echange X到队列Q1的绑定,binding key为black。 在这种情况下,这个direct exchange表现的像fanout类型的exchange一样,能够广播消息给所有匹配的队列。即具有routing key为black的消息将被传送到队列Q1和Q2

Emitting logs 发送日志

We'll use this model for our logging system. Instead of fanout we'll send messages to a directexchange. We will supply the log severity as a routing key. That way the receiving program will be able to select the severity it wants to receive. Let's focus on emitting logs first.

在日志系统中,我们使用direct类型的exchange,而不是fanout类型的。我们将消息发送到一个命名为x的direct exchange。把日志级别当做routing key。这样能实现接收程序将根据级别有选择性的接收日志,达到对不同级别的日志的不同处理。Error级别的消息保存到硬盘,warning、info级别的输出到屏幕上。

接下来我们重点关注如何publish 日志消息?

As always, we need to create an exchange first:

首先,我们创建一个direct类型的exchange,命名为EXCHANGE_NAME字符串的值

channel.exchangeDeclare(EXCHANGE_NAME, "direct");

And we're ready to send a message:

接下来准备发送消息,发送到具体EXCHANGE_NAME值的exchange,rounting key是具体的severity

channel.basicPublish(EXCHANGE_NAME, severity, null, message.getBytes());

To simplify things we will assume that 'severity' can be one of 'info', 'warning', 'error'.

假定日志级别severity是‘info’,'warning',‘error'

Subscribing  订阅日志

Receiving messages will work just like in the previous tutorial, with one exception - we're going to create a new binding for each severity we're interested in.

接收消息的部分大体和之前教程中的一样。

String queueName = channel.queueDeclare().getQueue();

for(String severity : argv){
  channel.queueBind(queueName, EXCHANGE_NAME, severity);
}

Putting it all together   最终的实现

The code for EmitLogDirect.Java class:

发送日志消息的EmitLogDirectJava.class

import com.rabbitmq.client.*;

import java.io.IOException;

public class EmitLogDirect {

    private static final String EXCHANGE_NAME = "direct_logs";

    public static void main(String[] argv)
                  throws java.io.IOException {

        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.exchangeDeclare(EXCHANGE_NAME, "direct");

        String severity = getSeverity(argv);
        String message = getMessage(argv);

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

        channel.close();
        connection.close();
    }
    //..
}

The code for ReceiveLogsDirect.java:

ReceiveLogsDirect.ava

import com.rabbitmq.client.*;

import java.io.IOException;

public class ReceiveLogsDirect {

  private static final String EXCHANGE_NAME = "direct_logs";

  public static void main(String[] argv) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare(EXCHANGE_NAME, "direct");
    String queueName = channel.queueDeclare().getQueue();

    if (argv.length < 1){
      System.err.println("Usage: ReceiveLogsDirect [info] [warning] [error]");
      System.exit(1);
    }

    for(String severity : argv){
      channel.queueBind(queueName, EXCHANGE_NAME, severity);
    }
    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

    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 '" + envelope.getRoutingKey() + "':'" + message + "'");
      }
    };
    channel.basicConsume(queueName, true, consumer);
  }
}

Compile as usual (see tutorial one for compilation and classpath advice). For convenience we'll use an environment variable $CP (that's %CP% on Windows) for the classpath when running examples.

javac -cp $CP ReceiveLogsDirect.java EmitLogDirect.java

If you want to save only 'warning' and 'error' (and not 'info') log messages to a file, just open a console and type:

java -cp $CP ReceiveLogsDirect warning error > logs_from_rabbit.log

If you'd like to see all the log messages on your screen, open a new terminal and do:

java -cp $CP ReceiveLogsDirect info warning error
# => [*] Waiting for logs. To exit press CTRL+C

And, for example, to emit an error log message just type:

java -cp $CP EmitLogDirect error "Run. Run. Or it will explode."
# => [x] Sent 'error':'Run. Run. Or it will explode.'

(Full source code for (EmitLogDirect.java source) and (ReceiveLogsDirect.java source))

Move on to tutorial 5 to find out how to listen for messages based on a pattern.


Routing  路由模式   (using the Java client)

In the previous tutorial we built a simple logging system. We were able to broadcast log messages to many receivers.

在上一篇教程中,我们构造了一个简单的日志系统。我们可以广播日志消息给所有的receivers

In this tutorial we're going to add a feature to it - we're going to make it possible to subscribe only to a subset of the messages. For example, we will be able to direct only critical error messages to the log file (to save disk space), while still being able to print all of the log messages on the console.

在本教程中,我们将为其添加一个功能 - consumer仅订阅消息的一部分,而不像上一篇教程中每个consumer会订阅RabbitMQ中所有的消息。 例如,我们将仅将关键的错误消息引导到日志文件(以节省磁盘空间),同时仍然能够在控制台上打印所有日志消息。

Bindings

In previous examples we were already creating bindings. You may recall code like:

在上一篇教程中,我们仅仅是将exchange和queue绑定在一起,并没有指定routing key

channel.queueBind(queueName, EXCHANGE_NAME, "");

A binding is a relationship between an exchange and a queue. This can be simply read as: the queue is interested in messages from this exchange.

绑定代表exchange和queue建立关系。 可以简单的理解为:队列想要订阅来自此exchange的消息

Bindings can take an extra routingKey parameter. To avoid the confusion with a basic_publishparameter we're going to call it a binding key. This is how we could create a binding with a key:

实际上,在绑定时可以带具体的routingKey 参数。上一篇教程因为我们用的是fanout类型的exchange,这个模式下routingKey被忽略,所以routingKey为空字符串。

其实这个参数的名称和basicPublish()的参数名是相同了。为了避免混淆,我们把它叫做binding key。

 Queue.BindOk queueBind(String queue, String exchange, String routingKey=>bindingKey) throws IOException;


 void basicPublish(String exchange, String routingKey, BasicProperties props, byte[] body) throws IOException;


绑定一个队列到exchange,binding key是black

channel.queueBind(queueName, EXCHANGE_NAME, "black");

The meaning of a binding key depends on the exchange type. The fanout exchanges, which we used previously, simply ignored its value.

对于fanout的exchange来说,这个参数是被忽略的。所以空字符串代替

Direct exchange

Our logging system from the previous tutorial broadcasts all messages to all consumers. We want to extend that to allow filtering messages based on their severity. For example we may want a program which writes log messages to the disk to only receive critical errors, and not waste disk space on warning or info log messages.

在上一个教程中日志记录系统会向所有消费者广播所有消息。现在我们希望将其扩展为消费者可以根据日志的级别进行过滤。 例如,我们可能仅仅是将Error级别的日志写入磁盘,而不会浪费warning或info级别的日志不做存储,以节省磁盘空间。

We were using a fanout exchange, which doesn't give us much flexibility - it's only capable of mindless broadcasting.

因此我们不能再使用fanout exchange,它不太灵活 - 只能无脑地广播所有消息给所有的消费者。

We will use a direct exchange instead. The routing algorithm behind a direct exchange is simple - a message goes to the queues whose binding key exactly matches the routing key of the message.

direct exchange能达到我们的目的。 direct exchange背后的路由算法其实很简单 - 消息会传递到bindingkey与消息携带的routingKey完全匹配的队列。

To illustrate that, consider the following setup:

In this setup, we can see the direct exchange X with two queues bound to it. The first queue is bound with binding key orange, and the second has two bindings, one with binding key black and the other one with green.

我们可以看到这个direct exchange X和两个队列绑定了。第一个队列Q1的binding key是orange,第二个队列的bingkey是black,green

In such a setup a message published to the exchange with a routing key orange will be routed to queue Q1. Messages with a routing key of black or green will Go to Q2. All other messages will be discarded.

如图,如果一个消息发布到exchange并且具有routingkey是orange,那消息将被路由到Q1队列。如果消息具有一个black或green的routing key将被路由到Q2。如果routing key不能够匹配到,消息将会丢弃。

Multiple bindings

It is perfectly legal to bind multiple queues with the same binding key. In our example we could add a binding between X and Q1 with binding key black. In that case, the direct exchange will behave like fanout and will broadcast the message to all the matching queues. A message with routing key black will be delivered to both Q1 and Q2.

使用相同的bindKey绑定多个队列是合法的。 在我们的示例中,我们添加一个echange X到队列Q1的绑定,binding key为black。 在这种情况下,这个direct exchange表现的像fanout类型的exchange一样,能够广播消息给所有匹配的队列。即具有routing key为black的消息将被传送到队列Q1和Q2

Emitting logs 发送日志

We'll use this model for our logging system. Instead of fanout we'll send messages to a directexchange. We will supply the log severity as a routing key. That way the receiving program will be able to select the severity it wants to receive. Let's focus on emitting logs first.

在日志系统中,我们使用direct类型的exchange,而不是fanout类型的。我们将消息发送到一个命名为x的direct exchange。把日志级别当做routing key。这样能实现接收程序将根据级别有选择性的接收日志,达到对不同级别的日志的不同处理。Error级别的消息保存到硬盘,warning、info级别的输出到屏幕上。

接下来我们重点关注如何publish 日志消息?

As always, we need to create an exchange first:

首先,我们创建一个direct类型的exchange,命名为EXCHANGE_NAME字符串的值

channel.exchangeDeclare(EXCHANGE_NAME, "direct");

And we're ready to send a message:

接下来准备发送消息,发送到具体EXCHANGE_NAME值的exchange,rounting key是具体的severity

channel.basicPublish(EXCHANGE_NAME, severity, null, message.getBytes());

To simplify things we will assume that 'severity' can be one of 'info', 'warning', 'error'.

假定日志级别severity是‘info’,'warning',‘error'

Subscribing  订阅日志

Receiving messages will work just like in the previous tutorial, with one exception - we're going to create a new binding for each severity we're interested in.

接收消息的部分大体和之前教程中的一样。

String queueName = channel.queueDeclare().getQueue();

for(String severity : argv){
  channel.queueBind(queueName, EXCHANGE_NAME, severity);
}

Putting it all together   最终的实现

The code for EmitLogDirect.Java class:

发送日志消息的EmitLogDirectJava.class

import com.rabbitmq.client.*;

import java.io.IOException;

public class EmitLogDirect {

    private static final String EXCHANGE_NAME = "direct_logs";

    public static void main(String[] argv)
                  throws java.io.IOException {

        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.exchangeDeclare(EXCHANGE_NAME, "direct");

        String severity = getSeverity(argv);
        String message = getMessage(argv);

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

        channel.close();
        connection.close();
    }
    //..
}

The code for ReceiveLogsDirect.java:

ReceiveLogsDirect.ava

import com.rabbitmq.client.*;

import java.io.IOException;

public class ReceiveLogsDirect {

  private static final String EXCHANGE_NAME = "direct_logs";

  public static void main(String[] argv) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare(EXCHANGE_NAME, "direct");
    String queueName = channel.queueDeclare().getQueue();

    if (argv.length < 1){
      System.err.println("Usage: ReceiveLogsDirect [info] [warning] [error]");
      System.exit(1);
    }

    for(String severity : argv){
      channel.queueBind(queueName, EXCHANGE_NAME, severity);
    }
    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

    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 '" + envelope.getRoutingKey() + "':'" + message + "'");
      }
    };
    channel.basicConsume(queueName, true, consumer);
  }
}

Compile as usual (see tutorial one for compilation and classpath advice). For convenience we'll use an environment variable $CP (that's %CP% on Windows) for the classpath when running examples.

javac -cp $CP ReceiveLogsDirect.java EmitLogDirect.java

If you want to save only 'warning' and 'error' (and not 'info') log messages to a file, just open a console and type:

java -cp $CP ReceiveLogsDirect warning error > logs_from_rabbit.log

If you'd like to see all the log messages on your screen, open a new terminal and do:

java -cp $CP ReceiveLogsDirect info warning error
# => [*] Waiting for logs. To exit press CTRL+C

And, for example, to emit an error log message just type:

java -cp $CP EmitLogDirect error "Run. Run. Or it will explode."
# => [x] Sent 'error':'Run. Run. Or it will explode.'

(Full source code for (EmitLogDirect.java source) and (ReceiveLogsDirect.java source))

Move on to tutorial 5 to find out how to listen for messages based on a pattern.


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值