中文文档
注意: 安装python2 下的 pika 版本 要低于1.0 (0.9.5--> 不行,
会报log不存在问题,需要使用0.12)
sudo rabbitmqctl list_queues #列出所有RabbitMQ队列
sudo service rabbitmq-server restart #重启rabbitmq服务
#!/usr/bin/env python
import pika
#跟本地机器的代理建立了连接。如果你想连接到其他机器的代理上,
#需要把代表本地的localhost改为指定的名字或IP地址。
connection =
pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
channel.queue_declare(queue='hello') #创建一个名为"hello"的队列用来将消息投递进去
channel.basic_publish(exchange='', #匿名的交换机
routing_key='hello', #队列名字
body='Hello World!')
print(" [x] Sent 'Hello World!'")
#在退出程序之前,我们需要确认网络缓冲已经被刷写、消息已经投递到RabbitMQ。
#通过安全关闭连接可以做到这一点。
connection.close()
#!/usr/bin/env python
import pika
connection =
pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
channel.queue_declare(queue='hello')
#从队列中获取消息相对来说稍显复杂。需要为队列定义一个回调(callback)函数。
#当我们获取到消息的时候,Pika库就会调用此回调函数。
#这个回调函数会将接收到的消息内容输出到屏幕上。
def callback(ch, method, properties, body):
print(" [x] Received %r" % body)
#告诉RabbitMQ这个回调函数将会从名为"hello"的队列中接收消息
channel.basic_consume(callback,
queue='hello',
# 关闭消息响应,收到相应后不删除队列中的数据
no_ack=True)
print(' [*] Waiting for messages. To exit press CTRL+C')
#运行一个用来等待消息数据并且在需要的时候运行回调函数的无限循环
channel.start_consuming()
#!/usr/bin/env python
import pika
import sys
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
channel = connection.channel()
#切换另一个新的队列,为了不让队列消失,需要把队列声明为持久化(durable)
#就可以确保在RabbitMq重启之后queue_declare队列不会丢失。
。
channel.queue_declare(queue='task_queue', durable=True)
message = ' '.join(sys.argv[1:]) or "Hello World!"
channel.basic_publish(exchange='',
routing_key='task_queue',
body=message,
#我们需要把我们的消息也要设为持久化——将delivery_mode的属性设为2
properties=pika.BasicProperties(
delivery_mode = 2, # make message persistent
))
print " [x] Sent %r" % (message,)
connection.close()
#!/usr/bin/env python
import pika
import time
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
channel = connection.channel()
channel.queue_declare(queue='task_queue', durable=True)
print ' [*] Waiting for messages. To exit press CTRL+C'
def callback(ch, method, properties, body):
print " [x] Received %r" % (body,)
time.sleep( body.count('.') )
print " [x] Done"
#当工作者(worker)完成了任务,就发送一个响应,rabbitmq 收到相应后会删除队列数据
ch.basic_ack(delivery_tag = method.delivery_tag)
#再同一时刻,不要发送超过1条消息给一个工作者(worker),直到它已经处理了上一条消息
#并且作出了响应。这样,RabbitMQ就会把消息分发给下一个空闲的工作者(worker)。
channel.basic_qos(prefetch_count=1)
channel.basic_consume(callback,
queue='task_queue')
channel.start_consuming()
$ sudo rabbitmqctl list_exchanges
Listing exchanges ...
logs fanout
amq.direct direct
amq.topic topic
amq.fanout fanout
amq.headers headers
...done.
#!/usr/bin/env python
import pika
import sys
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
channel = connection.channel()
#先创建一个fanout类型的交换机,命名为logs
channel.exchange_declare(exchange='logs',
exchange_type='fanout')
message = ' '.join(sys.argv[1:]) or "info: Hello World!"
channel.basic_publish(exchange='logs', #使用创建的交换机
routing_key='', #使用临时队列
body=message)
print " [x] Sent %r" % (message,)
connection.close()
#!/usr/bin/env python
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='logs',
exchange_type='fanout')
#当与消费者(consumer)断开连接的时候,这个队列应当被立即删除。
#exclusive标识符即可达到此目的。
result = channel.queue_declare(exclusive=True)
#获取默认的临时队列名字 eg:amq.gen-U0srCoW8TsaXjNh73pnVAw==
queue_name = result.method.queue
#告诉交换机如何发送消息给我们的队列。
#交换器和队列之间的联系我们称之为绑定(binding)
#使用rabbitmqctl list_bindings 列出所有现存的绑定
channel.queue_bind(exchange='logs',
queue=queue_name)
print ' [*] Waiting for logs. To exit press CTRL+C'
def callback(ch, method, properties, body):
print " [x] %r" % (body,)
channel.basic_consume(callback,
queue=queue_name,
no_ack=True)
channel.start_consuming()
#!/usr/bin/env python
import pika
import sys
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
channel = connection.channel()
'''
直连交换机(
1. 指定交换机类型:fanout,direct,topic
2. 指定接受的路由
)
'''
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()
#!/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()
使用
#如果你希望只是保存warning和error级别的日志到磁盘,只需要打开控制台并输入:
$ python receive_logs_direct.py warning error > logs_from_rabbit.log
#如果你希望所有的日志信息都输出到屏幕中,打开一个新的终端,然后输入:
$ python receive_logs_direct.py info warning error
[*] Waiting for logs. To exit press CTRL+C
#如果要触发一个error级别的日志,只需要输入:
$ python emit_log_direct.py error "Run. Run. Or it will explode."
[x] Sent 'error':'Run. Run. Or it will explode.'
eg : 我们创建了三个绑定:Q1的绑定键为 *.orange.*,Q2的绑定键为 *.*.rabbit 和 lazy.# 。
这三个绑定键被可以总结为:
Q1 对所有的桔黄色动物都感兴趣。
Q2 则是对所有的兔子和所有懒惰的动物感兴趣。
#!/usr/bin/env python
import pika
import sys
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='topic_logs',
type='topic')
routing_key = sys.argv[1] if len(sys.argv) > 1 else 'anonymous.info'
message = ' '.join(sys.argv[2:]) or 'Hello World!'
channel.basic_publish(exchange='topic_logs',
routing_key=routing_key,
body=message)
print " [x] Sent %r:%r" % (routing_key, message)
connection.close()
#!/usr/bin/env python
import pika
import sys
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='topic_logs',
type='topic')
result = channel.queue_declare(exclusive=True)
queue_name = result.method.queue
binding_keys = sys.argv[1:]
if not binding_keys:
print >> sys.stderr, "Usage: %s [binding_key]..." % (sys.argv[0],)
sys.exit(1)
for binding_key in binding_keys:
channel.queue_bind(exchange='topic_logs',
queue=queue_name,
routing_key=binding_key)
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()
使用
#执行下边命令 接收所有日志:
python receive_logs_topic.py "#"
#执行下边命令 接收来自”kern“设备的日志:
python receive_logs_topic.py "kern.*"
#执行下边命令 只接收严重程度为”critical“的日志:
python receive_logs_topic.py "*.critical"
#执行下边命令 建立多个绑定:
python receive_logs_topic.py "kern.*" "*.critical"
#执行下边命令 发送路由键为 "kern.critical" 的日志:
python emit_log_topic.py "kern.critical" "A critical kernel error"
RPC注意事项:
确保能够明确的搞清楚哪个函数是本地调用的,哪个函数是远程调用的。给你的系统编写文档。
保持各个组件间的依赖明确。处理错误案例。明了客户端改如何处理RPC服务器的宕机和长时间无响应情况。
当对避免使用RPC有疑问的时候。如果可以的话,你应该尽量使用异步管道来代替RPC类的阻塞。
结果被异步地推送到下一个计算场景。
回调队列
#为了接收到回复信息,客户端需要在发送请求的时候同时发送一个回调队列(callback queue)的地址。
result = channel.queue_declare(exclusive=True)
callback_queue = result.method.queue
channel.basic_publish(exchange='',
routing_key='rpc_queue',
properties=pika.BasicProperties(
# 回调队列
reply_to = callback_queue,
),
body=request)
消息属性
RPC 工作流程:
#!/usr/bin/env python
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
channel = connection.channel()
channel.queue_declare(queue='rpc_queue')
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
def on_request(ch, method, props, body):
n = int(body)
print " [.] fib(%s)" % (n,)
response = fib(n)
ch.basic_publish(exchange='',
routing_key=props.reply_to,
properties=pika.BasicProperties(correlation_id = \
props.correlation_id),
body=str(response))
ch.basic_ack(delivery_tag = method.delivery_tag)
channel.basic_qos(prefetch_count=1)
channel.basic_consume(on_request, queue='rpc_queue')
print " [x] Awaiting RPC requests"
channel.start_consuming()
服务器端代码相当简单:
#!/usr/bin/env python
import pika
import uuid
class FibonacciRpcClient(object):
def __init__(self):
self.connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
self.channel = self.connection.channel()
result = self.channel.queue_declare(exclusive=True)
self.callback_queue = result.method.queue
self.channel.basic_consume(self.on_response, no_ack=True,
queue=self.callback_queue)
def on_response(self, ch, method, props, body):
if self.corr_id == props.correlation_id:
self.response = body
def call(self, n):
self.response = None
self.corr_id = str(uuid.uuid4())
self.channel.basic_publish(exchange='',
routing_key='rpc_queue',
properties=pika.BasicProperties(
reply_to = self.callback_queue,
correlation_id = self.corr_id,
),
body=str(n))
while self.response is None:
#是一个等待消息的阻塞过程,连接的任何消息都可以使它脱离阻塞状态
self.connection.process_data_events()
return int(self.response)
fibonacci_rpc = FibonacciRpcClient()
print " [x] Requesting fib(30)"
response = fibonacci_rpc.call(30)
print " [.] Got %r" % (response,)
客户端代码稍微有点难懂:
使用
#启动服务器端:
$ python rpc_server.py
[x] Awaiting RPC requests
#运行客户端,请求一个fibonacci队列。
$ python rpc_client.py
[x] Requesting fib(30)