版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/haeasringnar/article/details/82716550
1、服务端代码
# rpc_server.py
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), # 将接收到的id发送过去
body=str(response) # 将方法返回的结果返回给客户端
)
# 进行消息确认,不确认会导致不能够释放没响应的消息,RabbitMQ就会占用越来越多的内存。
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()
2、客户端代码
# rpc_client.py
import pika
import uuid
# 定义一个客户端类
class FibonacciRpcClient(object):
def __init__(self):
# 初始化链接
self.connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
# 初始化管道
self.channel = self.connection.channel()
# 因为发布订阅用的是随机名队列,所以当与消费者断开连接的时候,这个队列应当被立即删除。exclusive标识符即可达到此目的。
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
# 初始化一个id并保存下来
self.corr_id = str(uuid.uuid4())
# 发送消息,将这个消息发送给服务端
self.channel.basic_publish(exchange='',
routing_key='rpc_queue',
properties=pika.BasicProperties(
# 发送回调的队列过去
reply_to = self.callback_queue,
# 发送id过去
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)
3、如何运行
先运行服务端:
python rpc_server.py
再运行客户端:
python rpc_client.py