RabbitMQ介绍

RabbitMQ是一个由erlang开发的AMQP(Advanced Message Queue )的开源实现的产品,RabbitMQ是一个消息代理,从“生产者”接收消息并传递消息至“消费者”,期间可根据规则路由、缓存、持久化消息。“生产者”也即message发送者以下简称P,相对应的“消费者”乃message接收者以下简称C,message通过queue由P到C,queue存在于RabbitMQ,可存储尽可能多的message,多个P可向同一queue发送message,多个C可从同一个queue接收message

  • 内部架构:

  • 说明

    • Message (消息):RabbitMQ 转发的二进制对象,包括Headers(头)、Properties (属性)和 Data (数据),其中数据部分不是必要的。Producer(生产者): 消息的生产者,负责产生消息并把消息发到交换机
    • Exhange的应用。

      • Consumer (消费者):使用队列 Queue 从 Exchange 中获取消息的应用。
      • Exchange (交换机):负责接收生产者的消息并把它转到到合适的队列
      • Queue (队列):一个存储Exchange 发来的消息的缓冲,并将消息主动发送给Consumer,或者 Consumer 主动来获取消息。见 1.4 部分的描述。

      • Binding (绑定):队列 和 交换机 之间的关系。Exchange 根据消息的属性和 Binding 的属性来转发消息。绑定的一个重要属性是 binding_key。

      • Connection (连接)和 Channel (通道):生产者和消费者需要和 RabbitMQ 建立 TCP 连接。一些应用需要多个connection,为了节省TCP 连接,可以使用 Channel,它可以被认为是一种轻型的共享 TCP 连接的连接。连接需要用户认证,并且支持 TLS (SSL)。连接需要显式关闭。

Python操作RabbitMQ

1.实现简单消息队列:

一个Product向queue发送一个message,一个Client从该queue接收message并打印

  • 发消息 product
import pika   

connection = pika.BlockingConnection(pika.ConnectionParameters(
host='127.0.0.1', port=5672, )) #定义连接池
channel = connection.channel()
channel.queue_declare(queue='test') #声明队列以向其发送消息消息
channel.basic_publish(exchange='', routing_key='test', body='Hello World!') #注意当未定义exchange时,routing_key需和queue的值保持一致
print('send success msg to rabbitmq')
connection.close() #关闭连接
  • 收消息,client
import pika

connection = pika.BlockingConnection(pika.ConnectionParameters(
host='127.0.0.1', port=5672))
channel = connection.channel() channel.queue_declare(queue='test') def callback(ch, method, properties, body):
'''回调函数,处理从rabbitmq中取出的消息'''
print(" [x] Received %r" % body) channel.basic_consume(callback,queue='test',no_ack=True)
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming() #开始监听 接受消息

执行效果:

#product端:
send success msg to rabbitmq #client端:
[*] Waiting for messages. To exit press CTRL+C
[x] Received b'Hello World!'
  • 消息确认

当客户端从队列中取出消息之后,可能需要一段时间才能处理完成,如果在这个过程中,客户端出错了,异常退出了,而数据还没有处理完成,那么非常不幸,这段数据就丢失了,因为rabbitmq默认会把此消息标记为已完成,然后从队列中移除,
消息确认是客户端从rabbitmq中取出消息,并处理完成之后,会发送一个ack告诉rabbitmq,消息处理完成,当rabbitmq收到客户端的获取消息请求之后,或标记为处理中,当再次收到ack之后,才会标记为已完成,然后从队列中删除。当rabbitmq检测到客户端和自己断开链接之后,还没收到ack,则会重新将消息放回消息队列,交给下一个客户端处理,保证消息不丢失,也就是说,RabbitMQ给了客户端足够长的时间来做数据处理。

在客户端使用no_ack来标记是否需要发送ack,默认是False,开启状态

product向rabbitmq发送两条消息:

import pika

connection = pika.BlockingConnection(pika.ConnectionParameters(
host='127.0.0.1', port=5672, )) #定义连接池
channel = connection.channel() #声明队列以向其发送消息消息 channel.queue_declare(queue='test')
channel.basic_publish(exchange='', routing_key='test', body='')
channel.basic_publish(exchange='', routing_key='test', body='')
channel.basic_publish(exchange='', routing_key='test', body='')
print('send success msg to rabbitmq')
connection.close() #关闭连接

客户端接受消息,不发送ack

import pika
import time connection = pika.BlockingConnection(pika.ConnectionParameters(
host='127.0.0.1', port=5672))
channel = connection.channel() channel.queue_declare(queue='test') def callback(ch, method, properties, body):
'''回调函数,处理从rabbitmq中取出的消息'''
print(" [x] Received %r" % body)
time.sleep(5)
#ch.basic_ack(delivery_tag = method.delivery_tag) #发送ack消息 channel.basic_consume(callback,queue='test',no_ack=False)
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming() #开始监听 接受消息

执行结果,发现消息并没有从队列中删除

第一次执行:
[*] Waiting for messages. To exit press CTRL+C
[x] Received b''
[x] Received b''
[x] Received b''
第二次执行:
[*] Waiting for messages. To exit press CTRL+C
[x] Received b''
[x] Received b''
[x] Received b''

加入ack之后:

import pika
import time connection = pika.BlockingConnection(pika.ConnectionParameters(
host='127.0.0.1', port=5672))
channel = connection.channel() channel.queue_declare(queue='test') def callback(ch, method, properties, body):
'''回调函数,处理从rabbitmq中取出的消息'''
print(" [x] Received %r" % body)
time.sleep(5)
ch.basic_ack(delivery_tag = method.delivery_tag) #发送ack消息 channel.basic_consume(callback,queue='test',no_ack=False)
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming() #开始监听 接受消息

运行结果:发现第二次运行队列中已经没有消息

第一次:
[*] Waiting for messages. To exit press CTRL+C
[x] Received b''
[x] Received b''
[x] Received b'
第二次:
[*] Waiting for messages. To exit press CTRL+C
  • 改变消息获取顺序

默认消息队列里的数据是按照顺序被消费者拿走,例如:消费者1 去队列中获取 奇数 序列的任务,消费者1去队列中获取 偶数 序列的任务。

channel.basic_qos(prefetch_count=1) 表示谁来谁取,不再按照奇偶数排列
默认情况:使用product往队列中放10个数字

import pika

connection = pika.BlockingConnection(pika.ConnectionParameters(
host='127.0.0.1', port=5672, )) #定义连接池
channel = connection.channel() #声明队列以向其发送消息消息 channel.queue_declare(queue='test')
for i in range(10):
channel.basic_publish(exchange='', routing_key='test', body=str(i))
print('send success msg[%s] to rabbitmq' %i)
connection.close() #关闭连接

运行结果;
send success msg[1] to rabbitmq
send success msg[2] to rabbitmq
send success msg[3] to rabbitmq
send success msg[4] to rabbitmq
send success msg[5] to rabbitmq
send success msg[6] to rabbitmq
send success msg[7] to rabbitmq
send success msg[8] to rabbitmq
send success msg[9] to rabbitmq

客户端1收消息:

import pika
import time connection = pika.BlockingConnection(pika.ConnectionParameters(
host='127.0.0.1', port=5672))
channel = connection.channel() channel.queue_declare(queue='test') def callback(ch, method, properties, body):
'''回调函数,处理从rabbitmq中取出的消息'''
print(" [x] Received %r" % body)
#time.sleep(5)
ch.basic_ack(delivery_tag = method.delivery_tag) #发送ack消息 channel.basic_consume(callback,queue='test',no_ack=False)
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming() #开始监听 接受消息

运行结果:
 [*] Waiting for messages. To exit press CTRL+C
[x] Received b''
[x] Received b''
[x] Received b''
[x] Received b''
[x] Received b''

客户端2收消息:和client1的区别是加了一个sleep(1)

import pika
import time connection = pika.BlockingConnection(pika.ConnectionParameters(
host='127.0.0.1', port=5672))
channel = connection.channel() channel.queue_declare(queue='test') def callback(ch, method, properties, body):
'''回调函数,处理从rabbitmq中取出的消息'''
print(" [x] Received %r" % body)
time.sleep(1)
ch.basic_ack(delivery_tag = method.delivery_tag) #发送ack消息 channel.basic_consume(callback,queue='test',no_ack=False)
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming() #开始监听 接受消息


执行结果:
 [*] Waiting for messages. To exit press CTRL+C
[x] Received b''
[x] Received b''
[x] Received b''
[x] Received b''
[x] Received b''

在两个客户端里加入channel.basic_qos(prefetch_count=1)参数

客户端1:

import pika
import time connection = pika.BlockingConnection(pika.ConnectionParameters(
host='127.0.0.1', port=5672))
channel = connection.channel() channel.queue_declare(queue='test') def callback(ch, method, properties, body):
'''回调函数,处理从rabbitmq中取出的消息'''
print(" [x] Received %r" % body)
##time.sleep(1)
ch.basic_ack(delivery_tag = method.delivery_tag) #发送ack消息 channel.basic_qos(prefetch_count=1) #添加不按顺序分配消息的参数
channel.basic_consume(callback,queue='test',no_ack=False)
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming() #开始监听 接受消息

执行效果:
[*] Waiting for messages. To exit press CTRL+C
[x] Received b''
[x] Received b''
[x] Received b''
[x] Received b''
[x] Received b''
[x] Received b''
[x] Received b''
[x] Received b''
[x] Received b''

客户端2:

import pika
import time connection = pika.BlockingConnection(pika.ConnectionParameters(
host='127.0.0.1', port=5672))
channel = connection.channel() channel.queue_declare(queue='test') def callback(ch, method, properties, body):
'''回调函数,处理从rabbitmq中取出的消息'''
print(" [x] Received %r" % body)
time.sleep(1)
ch.basic_ack(delivery_tag = method.delivery_tag) #发送ack消息 channel.basic_qos(prefetch_count=1)
channel.basic_consume(callback,queue='test',no_ack=False)
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming() #开始监听 接受消息


执行结果:
[*] Waiting for messages. To exit press CTRL+C
[x] Received b''

发现,加入channel.basic_qos(prefetch_count=1)参数之后,客户端2由于sleep了1s,所以只拿到了一个消息,其他的消息都被client1拿到了

  • 消息持久化 消息确认机制使得客户端在崩溃的时候,服务端消息不丢失,但是如果rabbitmq奔溃了呢?该如何保证队列中的消息不丢失? 此就需要product在往队列中push消息的时候,告诉rabbitmq,此队列中的消息需要持久化,用到的参数:durable=True,再次强调,Producer和client都应该去创建这个queue,尽管只有一个地方的创建是真正起作用的:
channel.basic_publish(exchange='',
routing_key="test",
body=message,
properties=pika.BasicProperties(
delivery_mode = 2, # make message persistent
))

具体代码:

product端:

import pika

connection = pika.BlockingConnection(pika.ConnectionParameters(
host='127.0.0.1', port=5672, )) #定义连接池
channel = connection.channel() #声明队列以向其发送消息消息 channel.queue_declare(queue='test_persistent',durable=True)
for i in range(10):
channel.basic_publish(exchange='', routing_key='test_persistent', body=str(i),properties=pika.BasicProperties(delivery_mode=2))
print('send success msg[%s] to rabbitmq' %i)
connection.close() #关闭连接

client端:

import pika
import time connection = pika.BlockingConnection(pika.ConnectionParameters(
host='127.0.0.1', port=5672))
channel = connection.channel() channel.queue_declare(queue='test_persistent',durable=True) def callback(ch, method, properties, body):
'''回调函数,处理从rabbitmq中取出的消息'''
print(" [x] Received %r" % body)
#time.sleep(5)
ch.basic_ack(delivery_tag = method.delivery_tag) #发送ack消息 channel.basic_qos(prefetch_count=1)
channel.basic_consume(callback,queue='test_persistent',no_ack=False)
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming() #开始监听 接受消息
注意:client端也需配置durable=True,否则将报下面错误: pika.exceptions.ChannelClosed: (406, "PRECONDITION_FAILED - parameters for queue 'test_persistent' in vhost '/' not equivalent")

配置完之后,发现product往rabbitmq端push消息之后,重启rabbitmq,消息依然存在

[root@dns ~]# rabbitmqctl list_queues
Listing queues ...
abc
abcd
hello2
test
test1
test_persistent
...done.
[root@dns ~]# /etc/init.d/rabbitmq-server restart
Restarting rabbitmq-server: SUCCESS
rabbitmq-server.
[root@dns ~]# rabbitmqctl list_queues
Listing queues ...
abc
abcd
hello2
test1
test_persistent
...done.

参考文档:参考文档:http://www.rabbitmq.com/tutorials/tutorial-two-python.html

2.使用Exchanges:

exchanges主要负责从product那里接受push的消息,根据product定义的规则,投递到queue中,是product和queue的中间件

  • Exchange 类型

    • direct 关键字类型
    • topic 模糊匹配类型
    • fanout 广播类型
  • 使用fanout实现发布订阅者模型

发布订阅和简单的消息队列区别在于,发布订阅会将消息发送给所有的订阅者,而消息队列中的数据被消费一次便消失。所以,RabbitMQ实现发布和订阅时,会为每一个订阅者创建一个队列,而发布者发布消息时,会将消息放置在所有相关队列中
订阅者:

import pika
import time connection = pika.BlockingConnection(pika.ConnectionParameters(
host='127.0.0.1', port=5672))
channel = connection.channel() channel.exchange_declare(exchange='test123',type='fanout') #定义一个exchange ,类型为fanout
rest = channel.queue_declare(exclusive=True) #创建一个随机队列,并启用exchange
queue_name = rest.method.queue #获取队列名
channel.queue_bind(exchange='test123',queue=queue_name) #将随机队列名和exchange进行绑定 def callback(ch, method, properties, body):
'''回调函数,处理从rabbitmq中取出的消息'''
print(" [x] Received %r" % body)
time.sleep(1)
ch.basic_ack(delivery_tag = method.delivery_tag) #发送ack消息 channel.basic_qos(prefetch_count=1)
channel.basic_consume(callback,queue=queue_name,no_ack=False)
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming() #开始监听 接受消息

发布者:

import pika

connection = pika.BlockingConnection(pika.ConnectionParameters(
host='127.0.0.1', port=5672, )) #定义连接池
channel = connection.channel() #声明队列以向其发送消息消息 channel.exchange_declare(exchange='test123',type='fanout')
for i in range(10):
channel.basic_publish(exchange='test123', routing_key='', body=str(i),properties=pika.BasicProperties(delivery_mode=2))
print('send success msg[%s] to rabbitmq' %i)
connection.close() #关闭连接

注意:
需先定义订阅者,启动订阅者,否则发布者publish到一个不存在的exchange是被禁止的。如果没有queue bindings exchange的话,msg是被丢弃的。

  • 使用direct 实现根据关键字发布消息

消息发布订阅者模型是发布者发布一条消息,所有订阅者都可以收到,现在rabbitmq还支持根据关键字发送,在发送消息的时候使用routing_key参数指定关键字,rabbitmq的exchange会判断routing_key的值,然后只将消息转发至匹配的队列,注意,此时需要订阅者先创建队列

配置参数为exchange的type=direct,然后定义routing_key即可

订阅者1: 订阅error,warning,info

import pika
import time connection = pika.BlockingConnection(pika.ConnectionParameters(
host='127.0.0.1', port=5672))
channel = connection.channel() channel.exchange_declare(exchange='test321',type='direct') #定义一个exchange ,类型为fanout
rest = channel.queue_declare(exclusive=True) #创建一个随机队列,并启用exchange
queue_name = rest.method.queue #获取队列名 severities = ['error','warning','info'] #定义三个routing_key for severity in severities:
channel.queue_bind(exchange='test321', routing_key=severity,queue=queue_name) def callback(ch, method, properties, body):
'''回调函数,处理从rabbitmq中取出的消息'''
print(" [x] Received %r" % body)
time.sleep(1)
ch.basic_ack(delivery_tag = method.delivery_tag) #发送ack消息 channel.basic_qos(prefetch_count=1)
channel.basic_consume(callback,queue=queue_name,no_ack=False)
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming() #开始监听 接受消息

订阅者2:订阅error,warning

import pika
import time connection = pika.BlockingConnection(pika.ConnectionParameters(
host='127.0.0.1', port=5672))
channel = connection.channel() channel.exchange_declare(exchange='test321',type='direct') #定义一个exchange ,类型为fanout
rest = channel.queue_declare(exclusive=True) #创建一个随机队列,并启用exchange
queue_name = rest.method.queue #获取队列名 severities = ['error','warning'] #定义两个routing_key for severity in severities:
channel.queue_bind(exchange='test321', routing_key=severity,queue=queue_name) def callback(ch, method, properties, body):
'''回调函数,处理从rabbitmq中取出的消息'''
print(" [x] Received %r" % body)
time.sleep(1)
ch.basic_ack(delivery_tag = method.delivery_tag) #发送ack消息 channel.basic_qos(prefetch_count=1)
channel.basic_consume(callback,queue=queue_name,no_ack=False)
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming() #开始监听 接受消息

发布者:

import pika

connection = pika.BlockingConnection(pika.ConnectionParameters(
host='127.0.0.1', port=5672, )) #定义连接池
channel = connection.channel() #声明队列以向其发送消息消息 channel.exchange_declare(exchange='test321',type='direct')
channel.basic_publish(exchange='test321', routing_key='info', body='info msg',properties=pika.BasicProperties(delivery_mode=2)) #发送info msg到 info routing_key
channel.basic_publish(exchange='test321', routing_key='error', body='error msg',properties=pika.BasicProperties(delivery_mode=2)) #发送error msg到 error routing_key print('send success msg[] to rabbitmq')
connection.close() #关闭连接**

效果:发现订阅者1和订阅者2都收到error消息,但是只有订阅者1收到了info消息

订阅者1:
[*] Waiting for messages. To exit press CTRL+C
[x] Received b'info msg'
[x] Received b'error msg'
订阅者2:
[*] Waiting for messages. To exit press CTRL+C
[x] Received b'error msg'
  • 使用topic实现模糊匹配发布消息

direct实现了根据自定义的routing_key来标示不同的queue,使用topic可以让队列绑定几个模糊的关键字,之后发送者将数据发送到exchange,exchange将传入”路由值“和 ”关键字“进行匹配,匹配成功,则将数据发送到指定队列

# 表示可以匹配 0 个 或 多个 单词
* 表示只能匹配 一个 单词 如:
fuzj.test 和fuzj.test.test
fuzj.# 会匹配到 fuzj.test 和fuzj.test.test
fuzj.* 只会匹配到fuzj.test

订阅者1: 使用#匹配

import pika
import time connection = pika.BlockingConnection(pika.ConnectionParameters(
host='127.0.0.1', port=5672))
channel = connection.channel() channel.exchange_declare(exchange='test333',type='topic') #定义一个exchange ,类型为fanout
rest = channel.queue_declare(exclusive=True) #创建一个随机队列,并启用exchange
queue_name = rest.method.queue #获取队列名 channel.queue_bind(exchange='test333', routing_key='test.#',queue=queue_name) def callback(ch, method, properties, body):
'''回调函数,处理从rabbitmq中取出的消息'''
print(" [x] Received %r" % body)
time.sleep(1)
ch.basic_ack(delivery_tag = method.delivery_tag) #发送ack消息 channel.basic_qos(prefetch_count=1)
channel.basic_consume(callback,queue=queue_name,no_ack=False)
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming() #开始监听 接受消息

订阅者2:使用*匹配

import pika
import time connection = pika.BlockingConnection(pika.ConnectionParameters(
host='127.0.0.1', port=5672))
channel = connection.channel() channel.exchange_declare(exchange='test333',type='topic') #定义一个exchange ,类型为fanout
rest = channel.queue_declare(exclusive=True) #创建一个随机队列,并启用exchange
queue_name = rest.method.queue #获取队列名 channel.queue_bind(exchange='test333', routing_key='test.*',queue=queue_name) def callback(ch, method, properties, body):
'''回调函数,处理从rabbitmq中取出的消息'''
print(" [x] Received %r" % body)
time.sleep(1)
ch.basic_ack(delivery_tag = method.delivery_tag) #发送ack消息 channel.basic_qos(prefetch_count=1)
channel.basic_consume(callback,queue=queue_name,no_ack=False)
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming() #开始监听 接受消息

发布者:

import pika

connection = pika.BlockingConnection(pika.ConnectionParameters(
host='127.0.0.1', port=5672, )) #定义连接池
channel = connection.channel() #声明队列以向其发送消息消息 channel.exchange_declare(exchange='test333',type='topic')
channel.basic_publish(exchange='test333', routing_key='test.123', body='test.123 msg',properties=pika.BasicProperties(delivery_mode=2))
channel.basic_publish(exchange='test333', routing_key='test.123.321', body=' test.123.321 msg',properties=pika.BasicProperties(delivery_mode=2)) print('send success msg[] to rabbitmq')
connection.close() #关闭连接

输出效果:

订阅者1:
[*] Waiting for messages. To exit press CTRL+C
[x] Received b'test.123 msg'
[x] Received b' test.123.321 msg' 订阅者2:
[*] Waiting for messages. To exit press CTRL+C
[x] Received b'test.123 msg'
  • 实现RPC

  • 过程:

    • 客户端 Client 设置消息的 routing key 为 Service 的队列 op_q,设置消息的 reply-to 属性为返回的 response 的目标队列 reponse_q,设置其 correlation_id 为以随机UUID,然后将消息发到 exchange。比如channel.basic_publish(exchange='', routing_key='op_q', properties=pika.BasicProperties(reply_to = reponse_q, correlation_id = self.corr_id),body=request)

    • Exchange 将消息转发到 Service 的 op_q

    • Service 收到该消息后进行处理,然后将response 发到 exchange,并设置消息的 routing_key 为原消息的 reply_to 属性,以及设置其 correlation_id 为原消息的 correlation_id 。

      ch.basic_publish(exchange='', routing_key=props.reply_to, properties=pika.BasicProperties(correlation_id = props.correlation_id), body=str(response))

    • Exchange 将消息转发到 reponse_q

    • Client 逐一接受 response_q 中的消息,检查消息的 correlation_id 是否为等于它发出的消息的correlation_id,是的话表明该消息为它需要的response。

  • 代码实现:

    • 服务端:
import pika
import subprocess
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='127.0.0.1', port=5672, )) #定义连接池 channel = connection.channel() #创建通道 channel.queue_declare(queue='rpc_queue') #创建rpc_queue队列 def operating(arg):
p = subprocess.Popen(arg, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) #执行系统命令
res = p.stdout.read() #取出标准输出
if not res: #判断是否有执行结果
responses_msg = p.stderr.read() #没有执行结果则取出标准错误输出
else:
responses_msg = res
return responses_msg def on_request(ch, method, props, body):
command = str(body,encoding='utf-8')
print(" [.] start Processing command : %s" % command)
response_msg = operating(body) #调用函数执行命令
ch.basic_publish(exchange='',
routing_key=props.reply_to,
properties=pika.BasicProperties(correlation_id = props.correlation_id),body=str(response_msg))
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()
  • 客户端
import pika
import uuid
import time class FibonacciRpcClient(object):
def __init__(self):
self.connection = pika.BlockingConnection(pika.ConnectionParameters(
host='127.0.0.1',port=5672,)) #定义连接池 self.channel = self.connection.channel() #创建通道 result = self.channel.queue_declare(exclusive=True,auto_delete=True) #创建客户端短接受服务端回应消息的队列,\exclusive=True表示只队列只允许当前链接进行连接,auto_delete=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, #correlation id可以理解为请求的唯一标识码
),
body=str(n))
while self.response is None: #不断从自己监听的队列里取消息,直到取到消息
self.connection.process_data_events()
return self.response.decode() fibonacci_rpc = FibonacciRpcClient() print(" [x] Requesting server" )
time.sleep(0.1)
while True:
command = input('>> ')
response = fibonacci_rpc.call(command)
print(" [.] Get %r \n" % response)

Python操作RabbitMQ的更多相关文章

  1. Python之路【第九篇】:Python操作 RabbitMQ、Redis、Memcache、SQLAlchemy

    Python之路[第九篇]:Python操作 RabbitMQ.Redis.Memcache.SQLAlchemy   Memcached Memcached 是一个高性能的分布式内存对象缓存系统,用 ...

  2. python - 操作RabbitMQ

    python - 操作RabbitMQ     介绍 RabbitMQ是一个在AMQP基础上完整的,可复用的企业消息系统.他遵循Mozilla Public License开源协议.MQ全称为Mess ...

  3. 文成小盆友python-num12 Redis发布与订阅补充,python操作rabbitMQ

    本篇主要内容: redis发布与订阅补充 python操作rabbitMQ 一,redis 发布与订阅补充 如下一个简单的监控模型,通过这个模式所有的收听者都能收听到一份数据. 用代码来实现一个red ...

  4. Python之路第十二天,高级(4)-Python操作rabbitMQ

    rabbitMQ RabbitMQ是一个在AMQP基础上完整的,可复用的企业消息系统.他遵循Mozilla Public License开源协议. MQ全称为Message Queue, 消息队列(M ...

  5. python操作RabbitMQ(不错)

    一.rabbitmq RabbitMQ是一个在AMQP基础上完整的,可复用的企业消息系统.他遵循Mozilla Public License开源协议. MQ全称为Message Queue, 消息队列 ...

  6. Python菜鸟之路:Python基础-Python操作RabbitMQ

    RabbitMQ简介 rabbitmq中文翻译的话,主要还是mq字母上:Message Queue,即消息队列的意思.rabbitmq服务类似于mysql.apache服务,只是提供的功能不一样.ra ...

  7. Python操作 RabbitMQ、Redis、Memcache

    Python操作 RabbitMQ.Redis.Memcache Memcached Memcached 是一个高性能的分布式内存对象缓存系统,用于动态Web应用以减轻数据库负载.它通过在内存中缓存数 ...

  8. Python 【第六章】:Python操作 RabbitMQ、Redis、Memcache、SQLAlchemy

    Memcached Memcached 是一个高性能的分布式内存对象缓存系统,用于动态Web应用以减轻数据库负载.它通过在内存中缓存数据和对象来减少读取数据库的次数,从而提高动态.数据库驱动网站的速度 ...

  9. Python操作 RabbitMQ、Redis、Memcache、SQLAlchemy

    Memcached Memcached 是一个高性能的分布式内存对象缓存系统,用于动态Web应用以减轻数据库负载.它通过在内存中缓存数据和对象来减少读取数据库的次数,从而提高动态.数据库驱动网站的速度 ...

随机推荐

  1. Database 'xxxx' is being recovered. Waiting until recovery is finished.

    巡检发现一个SQL SERVER Express 2005数据库备份时出现下面错误: Database 'xxxx' is being recovered. Waiting until recover ...

  2. DBCC SHRINKDATABASE xxxx was skipped because the file does not have enough free

    假设你创建一个数据库时,指定其初始化大小(SIZE )非常大.例如,如下测试案例所示 USE [master] GO   CREATE DATABASE [TEST] ON  PRIMARY  ( N ...

  3. 《CLR via C#》---枚举标志和标志位

    枚举类型 枚举类型定义了一组符号名称/值配对. 如 private enum Color /* : byte */ { White, // Assigned a value of 0 Red, // ...

  4. 【转】hive优化之--控制hive任务中的map数和reduce数

    一.    控制hive任务中的map数:  1.    通常情况下,作业会通过input的目录产生一个或者多个map任务. 主要的决定因素有: input的文件总个数,input的文件大小,集群设置 ...

  5. 在Windows上安装虚拟机详细图文教程

    用虚拟机来安装最新的软件,安装最新的系统等等比较保险,可以避免安装不顺利影响自己原来的系统和应用,想尝鲜又担心自己完全更换系统不适应的朋友可以尝试. 虚拟机下载:https://yunpan.cn/c ...

  6. Python进阶【第二篇】多线程、消息队列queue

    1.Python多线程.多进程 目的提高并发 1.一个应用程序,可以有多进程和多线程 2.默认:单进程,单线程 3.单进程,多线程 IO操作,不占用CPU python的多线程:IO操作,多线程提供并 ...

  7. 烂泥:学习tomcat之通过shell批量管理多个tomcat

    本文由ilanniweb提供友情赞助,首发于烂泥行天下 想要获得更多的文章,可以关注我的微信ilanniweb 公司的业务是使用tomcat做web容器,为了更有效的利用服务器的性能,我们一般部署多个 ...

  8. 搞ACM的你伤不起[转自RoBa]------(看一次,笑一次)

    RoBa原创,转载请注明出处  劳资六年前开始搞ACM啊!!!!!!!!!! 从此踏上了尼玛不归路啊!!!!!!!!!!!! 谁特么跟劳资讲算法是程序设计的核心啊!!!!!! 尼玛除了面试题就没见过用 ...

  9. 更改CentOS7的yum更新源

    1. 备份现有源: mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.bak 2.下载163源 wget h ...

  10. redis 源码阅读 数值转字符 longlong2str

    redis 在底层中会把long long转成string 再做存储. 主个功能是在sds模块里. 下面两函数是把long long 转成 char  和   unsiged long long 转成 ...