RabbitMQ使用介绍6—RPC
Posted venvive
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了RabbitMQ使用介绍6—RPC相关的知识,希望对你有一定的参考价值。
RPC
RPC既做消费者也做生产者
reply_to=self.callback_queue, #接收的队列
correlation_id=self.corr_id,#发送和接收到的问题的消息
rpc_client.py
# -*- coding: utf-8 -*-
'''
@Time : 2019/11/2 16:14
@Author : jiangzhiqin
'''
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(queue='',exclusive=True)
self.callback_queue = result.method.queue
self.channel.basic_consume(
queue=self.callback_queue,
on_message_callback=self.on_response,
auto_ack=True)
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_queque',
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)
rpc_server.py
# -*- coding: utf-8 -*-
'''
@Time : 2019/11/2 16:14
@Author : jiangzhiqin
'''
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(queue='rpc_queue',on_message_callback=on_request)
print("[x] Awaiting RPC requests")
channel.start_consuming()
以上是关于RabbitMQ使用介绍6—RPC的主要内容,如果未能解决你的问题,请参考以下文章
#yyds干货盘点#RabbitMQ示例6:远程过程调用RPC
使用 EventMachine 和 RabbitMQ 的 RPC