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

Bindings

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

 channel.queue_bind(exchange=exchange_name,
queue=queue_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.

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

 channel.queue_bind(exchange=exchange_name,
queue=queue_name,
routing_key='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 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 the script which is writing log 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 too much flexibility - it's only capable of mindless broadcasting.

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 keyof 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 blackand 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 script will be able to select the severity it wants to receive. Let's focus on emitting logs first.

Like always we need to create an exchange first:

 channel.exchange_declare(exchange='direct_logs',
type='direct')

And we're ready to send a message:

 channel.basic_publish(exchange='direct_logs',
routing_key=severity,
body=message)

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.

 result = channel.queue_declare(exclusive=True)
queue_name = result.method.queue for severity in severities:
channel.queue_bind(exchange='direct_logs',
queue=queue_name,
routing_key=severity)

Putting it all together

The code for emit_log_direct.py:

 #!/usr/bin/env python
import pika
import sys connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
channel = connection.channel() channel.exchange_declare(exchange='direct_logs',
type='direct') severity = sys.argv[1] if len(sys.argv) > 1 else 'info'
message = ' '.join(sys.argv[2:]) or 'Hello World!'
channel.basic_publish(exchange='direct_logs',
routing_key=severity,
body=message)
print " [x] Sent %r:%r" % (severity, message)
connection.close()

The code for receive_logs_direct.py:

 #!/usr/bin/env python
import pika
import sys connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
channel = connection.channel() channel.exchange_declare(exchange='direct_logs',
type='direct') result = channel.queue_declare(exclusive=True)
queue_name = result.method.queue severities = sys.argv[1:]
if not severities:
print >> sys.stderr, "Usage: %s [info] [warning] [error]" % \
(sys.argv[0],)
sys.exit(1) for severity in severities:
channel.queue_bind(exchange='direct_logs',
queue=queue_name,
routing_key=severity)

print ' [*] Waiting for logs. To exit press CTRL+C' def callback(ch, method, properties, body):
print " [x] %r:%r" % (method.routing_key, body,) channel.basic_consume(callback,
queue=queue_name,
no_ack=True) channel.start_consuming()

rabbitmq使用(四)的更多相关文章

  1. RabbitMQ(四) -- Routing

    RabbitMQ(四) -- Routing `rabbitmq`可以通过路由选择订阅者来发布消息. Bindings 通过下面的函数绑定Exchange与消息队列: channel.queue_bi ...

  2. 快速掌握RabbitMQ(二)——四种Exchange介绍及代码演示

    在上一篇的最后,编写了一个C#驱动RabbitMQ的简单栗子,了解了C#驱动RabbitMQ的基本用法.本章介绍RabbitMQ的四种Exchange及各种Exchange的使用场景. 1 direc ...

  3. RabbitMQ第四篇:Spring集成RabbitMQ

    前面几篇讲解了如何使用rabbitMq,这一篇主要讲解spring集成rabbitmq. 首先引入配置文件org.springframework.amqp,如下 <dependency> ...

  4. RabbitMQ的四种ExChange

    在message到达Exchange后,Exchange会根据route规则进入对应的Queue中,message可能进入一个Queue也可能进入对应多个Queue,至于进入哪个Queue或者是说哪个 ...

  5. RabbitMQ(四)

    RabbitMQ 配置 一.RabbitMQ 配置修改方式 1.修改环境变量 2.修改配置文件(只介绍这个) 3.修改运行时参数和政策 locate rabbitmq vi /var/log/rabb ...

  6. rabbitMQ第四篇:远程调用

    前言:前面我们讲解的都是本地服务器,现在如果需要远程计算机上运行一个函数,等待结果.这就是一个不同的故事了,这种模式通常被称为远程过程调用或者RPC. 本章教程我们使用RabbitMQ搭建一个RPC系 ...

  7. RabbitMQ (四) 路由选择 (Routing) -摘自网络

    本篇博客我们准备给日志系统添加新的特性,让日志接收者能够订阅部分消息.例如,我们可以仅仅将致命的错误写入日志文件,然而仍然在控制面板上打印出所有的其他类型的日志消息. 1.绑定(Bindings) 在 ...

  8. RabbitMQ (四) 路由选择 (Routing)

    上一篇博客我们建立了一个简单的日志系统,我们能够广播日志消息给所有你的接收者,如果你不了解,请查看:RabbitMQ (三) 发布/订阅.本篇博客我们准备给日志系统添加新的特性,让日志接收者能够订阅部 ...

  9. RabbitMQ笔记四:Binding,Queue,Message概念

    Binding详解   黄线部分就是binding Exchange与Exchange,Queue之间的虚拟连接,Binding中可以包含Routing key或者参数   创建binding 注意: ...

  10. rabbitmq系列四 之路由

    1.路由 在上一个的教程中,我们构建了一个简单的日志记录系统.我们能够向许多接收者广播日志消息. 在本次教程中,我们向该系统添加一些特性,比如,我只需要严重错误(erroe级别)的部分日志打印到磁盘文 ...

随机推荐

  1. Linux无权限上传文件解决办法

    无权限上传文件解决办法 1.当前登录的普通用户:user1/password1 2.切换到管理员(user2)用户: sudo su - user2 输入user2用户的密码:password2 或者 ...

  2. centos重启报错Umounting file systems:umount:/opt:device is busy

    系统重启报错: Umounting file systems:umount:/opt:device is busy 只能硬关机,回想一下最近刚安装了nod32 for linux x64的杀毒软件,开 ...

  3. IntelliJ IDEA 下的svn配置及使用的非常详细的图文总结

    首先,使用的时候,自己得先在电脑上安装个小乌龟.也就是svn啦. 第一步安装小乌龟. 如下: 具体安装好像没什么具体要求,一路next,就好. 如上图箭头所示,在安装 TortoiseSVN 的时候, ...

  4. LeetCode(29): 两数相除

    Medium! 题目描述: 给定两个整数,被除数 dividend 和除数 divisor.将两数相除,要求不使用乘法.除法和 mod 运算符. 返回被除数 dividend 除以除数 divisor ...

  5. poj2992 阶乘分解

    /* 将C(n,k)质因数分解,然后约束个数按公式计算 */ #include<iostream> #include<cstring> #include<cstdio&g ...

  6. java 知识体系

    java分成J2ME(移动应用开发),J2SE(桌面应用开发),J2EE(Web企业级应用),所以java并不是单机版的,只是面向对象语言.建议如果学习java体系的话可以这样去学习: *第一阶段:J ...

  7. 步步为营-71-asp.net的简单练习(图片处理)

    1 原有图片添加水印 1.1 封装一个类,用于获取文件路径 using System; using System.Collections.Generic; using System.IO; using ...

  8. Ext.js中自己扩展的EasyGrid

    这里只写了一些核心的代码,具体如下: Ext.ux.EasyGrid = Ext.extend(Ext.grid.GridPanel, { initComponent: function () { t ...

  9. JQUery利用Uploadify插件实现文件异步上传(十一)

    一:简介: Uploadify是JQuery的一个上传插件,实现的效果非常好,带进度显示 ,且Ajax异步,能一次性上传多个文件,功能强大,使用简单 1.支持单文件或多文件上传,可控制并发上传的文件数 ...

  10. 放弃WebView,使用Crosswalk做富文本编辑器

    版权声明: 欢迎转载,但请保留文章原始出处 作者:GavinCT 出处:http://www.cnblogs.com/ct2011/p/4100132.html 为什么放弃WebView Androi ...