liukaida 发表于 2018-8-14 11:59:19

3Python全栈之路系列之RabbitMQ-Eden

# _*_coding:utf-8_*_  
import pika
  
import uuid
  

  
class FibonacciRpcClient(object):
  
    def __init__(self):
  
      self.connection = pika.BlockingConnection(pika.ConnectionParameters(
  
            host='192.168.56.100'))
  

  
      self.channel = self.connection.channel()
  

  
      result = self.channel.queue_declare(exclusive=True)
  
      # 服务端返回处理完毕的数据新Queue名称
  
      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):
  
      # corr_id等于刚刚发送过去的ID,就代表这条消息是我的
  
      if self.corr_id == props.correlation_id:
  
            self.response = body
  

  
    def call(self, n):
  
      self.response = None
  
      # 生成一个唯一ID,相当于每个任务的ID
  
      self.corr_id = str(uuid.uuid4())
  
      self.channel.basic_publish(exchange='',
  
                                 routing_key='rpc_queue',
  
                                 properties=pika.BasicProperties(
  
                                       # 让服务端处理完成之后把数据放到这个Queue里面
  
                                       reply_to=self.callback_queue,
  
                                       # 加上一个任务ID
  
                                       correlation_id=self.corr_id,
  
                                 ),
  
                                 body=str(n))
  
      while self.response is None:
  
            # 不断地去Queue接受消息,但不是阻塞的,而是一直循环的去取
  
            self.connection.process_data_events()
  
      return int(self.response)
  

  
fibonacci_rpc = FibonacciRpcClient()
  
print(" Requesting fib(30)")
  
response = fibonacci_rpc.call(30)
  
print(" [.] Got %r" % response)
页: [1]
查看完整版本: 3Python全栈之路系列之RabbitMQ-Eden