rabbitmq RPC模式

publisher端:

import pika
import 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_message_callback = on_request, queue='rpc_queue',auto_ack = False)
 
print(" [x] Awaiting RPC requests")
channel.start_consuming()
View Code

subscriber端:

import pika
import uuid
import time
 
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(on_message_callback = self.on_response,
                                   queue=self.callback_queue, 
                                   auto_ack=False)
 
    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()
            #非阻塞版的start_consuming
            print("no msg...")
            time.sleep(0.5)
        return int(self.response)
 
fibonacci_rpc = FibonacciRpcClient()
 
print(" [x] Requesting fib(30)")
response = fibonacci_rpc.call(30)
print(" [.] Got %r" % response)
View Code

错误报告:406, 'PRECONDITION_FAILED - unknown delivery tag 1'

解决方案:

channel.basic_consume中设置auto_ack = False,即消费者在收到消息后会自动回复。

 

rabbitmq rpc模式即远程调用,客户端通过rabbitmq发送消息至服务器端,在服务器端调用各种函数对消息进行处理后将处理结果通过另一消息队列返回给客户端。客户端和服务器在此过程中既是发送方也是接收方。

 

posted on 2020-09-29 13:36  行而下的坏死  阅读(451)  评论(0)    收藏  举报