xuxiaohui9216 发表于 2018-8-11 11:25:35

Python 学习笔记 - RabbitMQ

#!/usr/bin/env python  
# -*- coding:utf-8 -*-
  
# Author Yuan Li
  
#!/usr/bin/env python
  
import pika
  
import uuid
  
class FibonacciRpcClient(object):
  

  
    def __init__(self):
  
            #绑定
  
      self.connection = pika.BlockingConnection(pika.ConnectionParameters(
  
                host='sydnagios'))
  
      self.channel = self.connection.channel()
  

  
      #生成随机队列
  
      result = self.channel.queue_declare(exclusive=True)
  
      self.callback_queue = result.method.queue
  

  
      #指定on_response从callback_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())
  

  
      #发送两个参数 reply_to和 correlation_id
  
      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()
  
      return int(self.response)
  

  
#实例化对象
  
fibonacci_rpc = FibonacciRpcClient()
  
print(" Requesting fib(30)")
  

  
#调用call,发送数据
  
response = fibonacci_rpc.call(30)
  
print(" [.] Got %r" % response)
页: [1]
查看完整版本: Python 学习笔记 - RabbitMQ