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:

  • 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

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

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),将匹配的消息发送到队列由消费者读取。

6、Routing的更多相关文章

  1. ASP.NET MVC 入门3、Routing

    本系列文章基于Microsoft ASP.NET MVC Beta. 在一个route中,通过在大括号中放一个占位符来定义( { and } ).当解析URL的时候,符号"/"和& ...

  2. [转]ASP.NET MVC 入门3、Routing

    在一个route中,通过在大括号中放一个占位符来定义( { and } ).当解析URL的时候,符号"/"和"."被作为一个定义符来解析,而定义符之间的值则匹配 ...

  3. ASP.Net MVC开发基础学习笔记:三、Razor视图引擎、控制器与路由机制学习

    一.天降神器“剃须刀” — Razor视图引擎 1.1 千呼万唤始出来的MVC3.0 在MVC3.0版本的时候,微软终于引入了第二种模板引擎:Razor.在这之前,我们一直在使用WebForm时代沿留 ...

  4. ASP.Net MVC开发基础学习笔记(3):Razor视图引擎、控制器与路由机制学习

    一.天降神器“剃须刀” — Razor视图引擎 1.1 千呼万唤始出来的MVC3.0 在MVC3.0版本的时候,微软终于引入了第二种模板引擎:Razor.在这之前,我们一直在使用WebForm时代沿留 ...

  5. 柯南君:看大数据时代下的IT架构(7)消息队列之RabbitMQ--案例(routing 起航)

    二.Routing(路由) (using the Java client) 在前面的学习中,构建了一个简单的日志记录系统,能够广播所有的日志给多个接收者,在该部分学习中,将添加一个新的特点,就是可以只 ...

  6. Spring Cloud Zuul网关 Filter、熔断、重试、高可用的使用方式。

    时间过的很快,写springcloud(十):服务网关zuul初级篇还在半年前,现在已经是2018年了,我们继续探讨Zuul更高级的使用方式. 上篇文章主要介绍了Zuul网关使用模式,以及自动转发机制 ...

  7. Angular基础(七) HTTP & Routing

    ​ 一.HTTP a)Angular提供了自己的HTTP库来调用外部API,为了能够在等待API响应的过程中继续与界面交互,采用异步HTTP请求的方式. b)Get请求,首先导入Http, Respo ...

  8. 4.1 Routing -- Introduction

    一.Routing 1. 当用户与应用程序交互时,它会经过很多状态.Ember.js为你提供了有用的工具去管理它的状态和扩展你的app. 2. 要理解为什么这是重要的,假设我们正在编写一个Web应用程 ...

  9. RabbitMQ---3、c#实现

    1.EasyNetQ组件的使用 EasyNetQ组件的使用方式比较简单,跟很多组件都类似,例如:建立连接,进行操作做等等,对于EasyNetQ组件也是如此.(mq的升级,用于简化rabbitmq应用代 ...

随机推荐

  1. ENVOIA

    1,ENVOIA 组织架构讲解 2,开发中的各文件详细讲解 3,系统Data Model讲解 ENOVIA 2012 Online doc文档简介. 介绍ENOVIA组织架构. 介绍ENOVIA前身M ...

  2. 7、zabbix自定义监控阈值-前端页面报警

    找个值监控一下: #监控passwd #默认是间隔是1小时,我们改成10秒,下面我们要把报警打开 #我们在被监控上的主机上创建一个新用户,过10秒,界面上就会报警了 ----------------- ...

  3. c# 第33节 类的封装--访问修饰符

    本节内容: 1:封装的简介 2:封装怎么实现 3:访问修饰符 1:封装的简介 2:封装怎么实现 3:访问修饰符 4:访问修饰符注意点

  4. Pwn-TestYourMemory

    题目地址 https://dn.jarvisoj.com/challengefiles/memory.838286edf4b832fd482d58ff1c217561 32位的程序,有NX保护,拖到I ...

  5. pwn-Stack Overflow

    地址 https://cgctf.nuptsast.com/challenges#Pwn 先观察一下,是一个32位的程序,而且只开了NX保护 用IDA看看伪代码,重点在message和pwnme这两个 ...

  6. 《anchor-based v.s. anchor-free》

    作者:青青子衿链接:https://www.zhihu.com/question/356551927/answer/926659692来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商业转载 ...

  7. <Math> 258 43

    258. Add Digits class Solution { public int addDigits(int num) { if(num == 0) return 0; if(num % 9 = ...

  8. 研究是一门艺术 (韦恩·C·布斯, 格雷戈里·G·卡洛姆, 约瑟夫·M·威廉姆斯 著)

    第一部分 研究,研究者与读者 前言: 开始一个研究计划 (已看) 第一章 以书面形式来思考 (已看) 第二章 与读者建立联系 第二部分 提问题,找答案 前言: 规划你的研究计划 第三章 从题目到问题 ...

  9. webrtc笔记(4): kurento 部署

    kurento是一个开源的webrtc mcu服务器,按官方的文档,建议在ubtntu上安装,过程如下: 注:建议先切换到root身份,如果不是root身份登录的,下列命令,请自行加上sudo . 另 ...

  10. flink 注册函数示例

    需求 (filter): 现在有这么一个需求,统计出现在纽约的行车记录.这里我们需要进行一个过滤的操作,我们需要有个自定义的 UDF ,具体思路是,表里面有经度和维度这两个字段,通过这个可以来开发一个 ...