rabbitmq使用(四)
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使用(四)的更多相关文章
- RabbitMQ(四) -- Routing
RabbitMQ(四) -- Routing `rabbitmq`可以通过路由选择订阅者来发布消息. Bindings 通过下面的函数绑定Exchange与消息队列: channel.queue_bi ...
- 快速掌握RabbitMQ(二)——四种Exchange介绍及代码演示
在上一篇的最后,编写了一个C#驱动RabbitMQ的简单栗子,了解了C#驱动RabbitMQ的基本用法.本章介绍RabbitMQ的四种Exchange及各种Exchange的使用场景. 1 direc ...
- RabbitMQ第四篇:Spring集成RabbitMQ
前面几篇讲解了如何使用rabbitMq,这一篇主要讲解spring集成rabbitmq. 首先引入配置文件org.springframework.amqp,如下 <dependency> ...
- RabbitMQ的四种ExChange
在message到达Exchange后,Exchange会根据route规则进入对应的Queue中,message可能进入一个Queue也可能进入对应多个Queue,至于进入哪个Queue或者是说哪个 ...
- RabbitMQ(四)
RabbitMQ 配置 一.RabbitMQ 配置修改方式 1.修改环境变量 2.修改配置文件(只介绍这个) 3.修改运行时参数和政策 locate rabbitmq vi /var/log/rabb ...
- rabbitMQ第四篇:远程调用
前言:前面我们讲解的都是本地服务器,现在如果需要远程计算机上运行一个函数,等待结果.这就是一个不同的故事了,这种模式通常被称为远程过程调用或者RPC. 本章教程我们使用RabbitMQ搭建一个RPC系 ...
- RabbitMQ (四) 路由选择 (Routing) -摘自网络
本篇博客我们准备给日志系统添加新的特性,让日志接收者能够订阅部分消息.例如,我们可以仅仅将致命的错误写入日志文件,然而仍然在控制面板上打印出所有的其他类型的日志消息. 1.绑定(Bindings) 在 ...
- RabbitMQ (四) 路由选择 (Routing)
上一篇博客我们建立了一个简单的日志系统,我们能够广播日志消息给所有你的接收者,如果你不了解,请查看:RabbitMQ (三) 发布/订阅.本篇博客我们准备给日志系统添加新的特性,让日志接收者能够订阅部 ...
- RabbitMQ笔记四:Binding,Queue,Message概念
Binding详解 黄线部分就是binding Exchange与Exchange,Queue之间的虚拟连接,Binding中可以包含Routing key或者参数 创建binding 注意: ...
- rabbitmq系列四 之路由
1.路由 在上一个的教程中,我们构建了一个简单的日志记录系统.我们能够向许多接收者广播日志消息. 在本次教程中,我们向该系统添加一些特性,比如,我只需要严重错误(erroe级别)的部分日志打印到磁盘文 ...
随机推荐
- Linux电源管理【转】
转自:http://www.cnblogs.com/sky-zhang/archive/2012/06/05/2536807.html PM notifier机制: 应用场景: There are s ...
- Python3学习笔记25-logging模块
logging模块,Python自带用来记录日志的模块. 因为工作需要用到关于日志的,最近一直都在看关于日志模块的东西,百度了很多文章,可惜都是看的让人一头雾水,最后运气不错,找到一篇很详细的文章.传 ...
- Python创建、删除桌面、启动组快捷方式的例子分享
一.Python创桌面建快捷方式的2个例子 例子一: 代码如下: import osimport pythoncomfrom win32com.shell import shell from w ...
- maven名词解释
Maven名词解释 Project:任何你想build的事物,Maven都可以认为它们是工程.这些工程被定义为工程对象模型(POM,Poject Object Model).一个工程可以依赖其它的工程 ...
- eclipse自动添加注释
自动添加注释 快捷键:alt shift jwindows-->preference Java-->Code Style-->Code Templates code-->new ...
- VS C# xamarin 开发android 调试正常 发布分发后运行闪退出错
我强烈推荐大家如果不是很有必要就不要引用一些.NET STD的库,比如json库newtonsoft.JSON,直接引用官方的system.Json就足够了,否则会导致体积变得巨大 好了废话不多说,这 ...
- Linux(CentOS7)安装zip、unzip命令
安装命令: yum install -y unzip zip
- eol-last的相关知识
eslint “eol-last”:0 文件末尾强制换行(就是代码结尾处,要来个空格,相当于加一行,设置为0就可以了) ./src/main.js error eol-last Newline ...
- LeetCode(60): 第k个排列
Medium! 题目描述: 给出集合 [1,2,3,…,n],其所有元素共有 n! 种排列. 按大小顺序列出所有排列情况,并一一标记,当 n = 3 时, 所有排列如下: "123" ...
- Javascript面向对象基础(二)
一: 用定义函数的方式定义类在面向对象的思想中,最核心的概念之一就是类.一个类表示了具有相似性质的一类事物的抽象,通过实例化一个类,可以获得属于该类的一个实例,即对象.在JavaScript中定义一个 ...