rpc_client.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. #!/usr/bin/env python
  2. import pika
  3. import uuid
  4. class FibonacciRpcClient(object):
  5. def __init__(self):
  6. self.connection = pika.BlockingConnection(
  7. pika.ConnectionParameters(host="localhost")
  8. )
  9. self.channel = self.connection.channel()
  10. result = self.channel.queue_declare(queue="", exclusive=True)
  11. self.callback_queue = result.method.queue
  12. self.channel.basic_consume(
  13. queue=self.callback_queue,
  14. on_message_callback=self.on_response,
  15. auto_ack=True,
  16. )
  17. def on_response(self, ch, method, props, body):
  18. if self.corr_id == props.correlation_id:
  19. self.response = body
  20. def call(self, n):
  21. self.response = None
  22. self.corr_id = str(uuid.uuid4())
  23. self.channel.basic_publish(
  24. exchange="",
  25. routing_key="rpc_queue",
  26. properties=pika.BasicProperties(
  27. reply_to=self.callback_queue, correlation_id=self.corr_id
  28. ),
  29. body=str(n),
  30. )
  31. while self.response is None:
  32. self.connection.process_data_events()
  33. return int(self.response)
  34. fibonacci_rpc = FibonacciRpcClient()
  35. for n in range(10, 30, 5):
  36. print(" [x] Requesting fib({0})".format(n))
  37. response = fibonacci_rpc.call(n)
  38. print(" [.] Got %r" % response)