190225RabbitMQ
一、简单的RabbitMQ示例
- 生产者
# Author:Li Dongfei
import pika
connection = pika.BlockingConnection(
pika.ConnectionParameters('localhost')
) #建立一个连接
channel = connection.channel() #声明一个管道
channel.queue_declare(queue='hello') #生成一个queue
channel.basic_publish(exchange='',
routing_key='hello', #queue名字
body='Hello World!')
print(" [x] Sent 'Hello World!'")
connection.close()
- 消费者
# Author:Li Dongfei
import pika
connection = pika.BlockingConnection(
pika.ConnectionParameters('localhost')
)
channel = connection.channel()
channel.queue_declare(queue='hello')
def callback(ch, method, properties, body):
print("-->", ch, method, properties)
print(" [x] Received %r" %body)
channel.basic_consume(callback, #开始消费消息,如果收到消息就调用callback函数来处理消息
queue='hello',
no_ack=True
)
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming() #开始收消息
二、RabbitMQ命令行工具
C:\>cd C:\Program Files\RabbitMQ Server\rabbitmq_server-3.7.12\sbin
C:\Program Files\RabbitMQ Server\rabbitmq_server-3.7.12\sbin>rabbitmqctl.bat list_queues #列出当前的queue
三、rabbitmq持久化
- 队列持久化
channel.queue_declare(queue='hello', durable=True) #durable=True声明队列持久化
- 消息持久化
channel.basic_publish(exchange='',
routing_key='hello', #queue名字
body='Hello World!',
properties=pika.BasicProperties(
delivery_mode=2 #消息持久化
))
四、消息调度
- 在消费者中定义
channel.basic_qos(prefetch_count=1) #只要当前有一条消息在处理则不要给我发消息
五、广播模式
- fanout:所有bind到此exchange的queue都可以接受消息
- 订阅/发布
生成者
# Author:Li Dongfei
import pika
connection = pika.BlockingConnection(
pika.ConnectionParameters('localhost')
)
channel = connection.channel()
channel.exchange_declare(exchange='logs',
exchange_type='fanout')
message = "info: Hello World!"
channel.basic_publish(exchange='logs',
routing_key='',
body=message)
print(" [x] Sent %r" %message)
connection.close()
消费者
# Author:Li Dongfei
import pika
connection = pika.BlockingConnection(
pika.ConnectionParameters('localhost')
)
channel = connection.channel()
channel.exchange_declare(exchange='logs',
exchange_type='fanout')
result = channel.queue_declare(exclusive=True) #exclusive 唯一的
queue_name = result.method.queue
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()
- direct:通过routingKey和exchange决定的哪个唯一的queue可以接受消息
生产者
# Author:Li Dongfei
import pika, sys
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'
))
channel = connection.channel()
channel.exchange_declare(exchange='direct_logs',
exchange_type='direct')
serverity = 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=serverity,
body=message)
print(" [x] Sent %r:%r" %(serverity, message))
connection.close()
消费者
# Author:Li Dongfei
import pika, sys
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='direct_logs',
exchange_type='direct')
result = channel.queue_declare(exclusive=True)
queue_name = result.method.queue
serverities = sys.argv[1:]
if not serverities:
sys.stderr.write("Usage: %s [info] [warning] [error]\n" %sys.argv[0])
sys.exit(1)
for serverity in serverities:
channel.queue_bind(exchange='direct_logs',
queue=queue_name,
routing_key=serverity)
print(' [*] Wating 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()
topic:所有符合routingKey的routingKey所bind的queue可以接受消息
六、rabbitMQ rpc
- client
# Author:Li Dongfei
import pika, uuid
class FibonacciTpcClient(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 = FibonacciTpcClient()
print(" [x] Requesting fib(30)")
response = fibonacci_rpc.call(30)
print(" [.] Got %r" %response)
- server
# Author:Li Dongfei
import pika, time
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] Awatiing RPC requests")
channel.start_consuming()
190225RabbitMQ的更多相关文章
随机推荐
- string的深入理解
本文只是个人总结见解,勿喷 首先肯定的是string是引用类型 string s_a = "yhc"; string s_b = s_a; if(s_a.Equals(s_b)) ...
- PHP下生成非重复的id
PHP在多进程运行的情况下,如果不采用内存锁或者文件锁,基本没办法能解决生成唯一Id的问题.试过了静态变量.单例模式等等.查询到php里的uniqid()函数,最后还是找到了一个折中方式,虽然还是有可 ...
- CSS秘密花园:多边框
今天在查询CSS3动画相关资料时偶然发现这个,感觉有时还是挺方便的.原文链接:http://www.w3cplus.com/css3/css-secrets/multiple-borders.html ...
- __sync_fetch_and_add系列
__sync_fetch_and_add系列一共有十二个函数,有加/减/与/或/异或/等函数的原子性操作函数,__sync_fetch_and_add,顾名思义,先fetch,然后自加,返回的是自加以 ...
- 在centos 下安装配置基于gitosis 的git 服务
前言 这里我用的系统是centos 6.2, 在服务器上的准备工作(服务器IP为10.0.2.8 ): 1.安装 openssh服务器与客户端工具 $ sudo yum install openssh ...
- Linux 搭建NFS文件服务器实现文件共享
我们接着玩Linux,O(∩_∩)O哈哈~ 1.什么是nfs NFS(Network File System)即网络文件系统,是FreeBSD支持的文件系统中的一种,它允许网络中的计算机之间通过TCP ...
- Docker学习笔记_Dockerfile基本知识
Dockerfile由一行行命令语句组成,并支持以#开头的注释行. 1.编写一个Dockerfile文件 创建一个空的Docker工作目录,进入该目录,使用sudo vim Dockerfile指令新 ...
- eclipse——执行Maven命令
右键pom.xml文件 点击 m2 Maven build... 输入要执行的命令,点击Run 控制台会打印maven运行过程
- 基于任务的异步编程模式,Task-based Asynchronous Pattern
术语: APM 异步编程模型,Asynchronous Programming Model,其中异步操作由一对 Begin/End 方法(如 FileStream.BeginRea ...
- HDU 4081 Peach Blossom Spring (最小生成树+dfs)
题意:给定一个 n 个点和相应的权值,要求你用 n-1 条边连接起来,其中一条边是魔法边,不用任何费用,其他的边是长度,求该魔法边的两端的权值与其他边费用的尽量大. 析:先求出最小生成树,然后再枚举每 ...