rpc_server.py 903 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. #!/usr/bin/env python
  2. import pika
  3. # https://www.rabbitmq.com/tutorials/tutorial-six-python.html
  4. connection = pika.BlockingConnection(
  5. pika.ConnectionParameters(host='localhost'))
  6. channel = connection.channel()
  7. channel.queue_declare(queue='rpc_queue')
  8. def fib(n):
  9. if n== 0:
  10. return 0
  11. elif n == 1:
  12. return 1
  13. else:
  14. return fib(n-1) + fib(n-2)
  15. def on_request(ch, method, props, body):
  16. n = int(body)
  17. print(" [.] fib(%s)" % n)
  18. response = fib(n)
  19. ch.basic_publish(exchange='',
  20. routing_key=props.reply_to,
  21. properties=pika.BasicProperties(correlation_id = props.correlation_id),
  22. body=str(response))
  23. ch.basic_ack(delivery_tag=method.delivery_tag)
  24. channel.basic_qos(prefetch_count=1)
  25. channel.basic_consume(queue='rpc_queue', on_message_callback=on_request)
  26. print( "[x] Awaiting RPC requests")
  27. channel.start_consuming()