6、Routing

Routing

  • In the previous tutorial we built a simple logging system. We were able to broadcast log messages to many 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'll be able to direct only critical error messages to the log file,while still being able to print all of the log messages on the console.

Bindings

  • In previous examples we were already creating bindings. You may recall code like:
  •   channel.queueBind(queueName,EXCHANGE_NAME,"");
    
  • A binding is a relationship between exchange and queue.This can ba simply read as: the queue is interested in messages from this exchange.
  • Bindings can take an extra routingKey parameter.To avoid the confusion with a basic_publish parameter we're going to call it a binding key.This is how we could create a binding with a key:
  •   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.

Direct exchange

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

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

  • We will use a direct exchage 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.

  • To illustrate that,consider the following setup:

    • 6、Routing
  • 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.

  • 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.

Multiple bindings

  • 6、Routing

  • 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.

Emitting logs

  • We'll use this model for our logging system. Instead of fanout we'll send messages to a direct exchange.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.
  • As always, we need to create an exchange first:
  •   channel.exchangeDeclare(EXCHANGE_NAME, "direct");
    
  • And we're ready to send a message:
    channel.basicPublish(EXCHANGE_NAME, severity, null, message.getBytes())
    
  • To simplify things we will assume that 'severity' can be one of '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);
      }
    
  • 6、Routing

Code

  •   public class EmitLogDirect {
          private static Log log = LogFactory.getLog(EmitLogDirect.class);
          private static final String EXCHANGE_NAME="direct_logs";
          public static void main(String[] argv)
          {
              ConnectionFactory connFactory = new ConnectionFactory();
              connFactory.setHost("localhost");
              Connection conn=null;
              Channel channel=null;
              try {
                  conn=connFactory.newConnection();
                  channel=conn.createChannel();
                  channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.DIRECT);
                  String[] severity={"info","warning","error"};
                  String message="hello,world";
                  for(String s:severity)
                  {
                      channel.basicPublish(EXCHANGE_NAME,s,null,message.getBytes());
                      System.out.println("sent:"+s+" "+message);
                  }
    
              } catch (IOException e) {
                  log.error(e);
              } catch (TimeoutException e) {
                  log.error(e);
              } finally {
                  if (channel!=null)
                  {
                      try {
                          channel.close();
                      } catch (IOException e) {
                          log.error(e);
                      } catch (TimeoutException e) {
                          log.error(e);
                      }
                  }
                  if (conn!=null)
                  {
                      try {
                          conn.close();
                      } catch (IOException e) {
                          log.error(e);
                      }
                  }
              }
          }
      }
      public class ReceiveLogDirect {
          private static Log log= LogFactory.getLog(ReceiveLogDirect.class);
          private static final String EXCHANGE_NAME="direct_logs";
          public static void main(String[] argv)
          {
              ConnectionFactory connFactory = new ConnectionFactory();
              connFactory.setHost("localhost");
              /*Connection conn=null;
              Channel channel=null;*/
              try {
                  final Connection conn=connFactory.newConnection();
                  final Channel channel=conn.createChannel();
                  channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.DIRECT);
                  String queueName=channel.queueDeclare().getQueue();
    
                  String[] severity={"info","warning","error"};
                  for (String s:severity)
                  {
                      channel.queueBind(queueName,EXCHANGE_NAME,s);
                  }
                  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("receive:"+envelope.getRoutingKey()+" "+message);
                          try {
                              Thread.sleep(1000);
                          } catch (InterruptedException e) {
                              log.error(e);
                          }finally {
                              channel.basicAck(envelope.getDeliveryTag(),false);
                          }
                      }
                  };
                  channel.basicConsume(queueName,false,consumer);
              } catch (IOException e) {
                  log.error(e);
              } catch (TimeoutException e) {
                  log.error(e);
              } finally {
              }
          }
      }
    
  • Firstly,run ReceiveLogDirect.java 进行消息监听
  • Secondly,run EmitLogDirect.java 发送消息

Summary

  • 生产者将消息发送到路由器,然后消费者创建队列绑定到路由器(通过routing key),接着路由器将生产者发送的消息与消费者创建的队列进行匹配(使用binding key也就是routing key),将匹配的消息发送到队列由消费者读取。