2015-10-22 01:09:30 +00:00
|
|
|
#!/usr/bin/env python
|
|
|
|
|
2022-04-14 11:02:52 +00:00
|
|
|
from __future__ import annotations
|
|
|
|
|
2021-07-20 13:07:49 +00:00
|
|
|
from kombu import Connection, Consumer, Producer, Queue, uuid
|
2015-10-22 01:09:30 +00:00
|
|
|
|
|
|
|
|
2020-07-13 13:58:06 +00:00
|
|
|
class FibonacciRpcClient:
|
2015-10-22 01:09:30 +00:00
|
|
|
|
|
|
|
def __init__(self, connection):
|
|
|
|
self.connection = connection
|
|
|
|
self.callback_queue = Queue(uuid(), exclusive=True, auto_delete=True)
|
|
|
|
|
|
|
|
def on_response(self, message):
|
|
|
|
if message.properties['correlation_id'] == self.correlation_id:
|
|
|
|
self.response = message.payload['result']
|
|
|
|
|
|
|
|
def call(self, n):
|
|
|
|
self.response = None
|
|
|
|
self.correlation_id = uuid()
|
|
|
|
with Producer(self.connection) as producer:
|
|
|
|
producer.publish(
|
|
|
|
{'n': n},
|
|
|
|
exchange='',
|
|
|
|
routing_key='rpc_queue',
|
|
|
|
declare=[self.callback_queue],
|
2016-11-10 17:58:50 +00:00
|
|
|
reply_to=self.callback_queue.name,
|
2015-10-22 01:09:30 +00:00
|
|
|
correlation_id=self.correlation_id,
|
|
|
|
)
|
|
|
|
with Consumer(self.connection,
|
|
|
|
on_message=self.on_response,
|
|
|
|
queues=[self.callback_queue], no_ack=True):
|
|
|
|
while self.response is None:
|
|
|
|
self.connection.drain_events()
|
|
|
|
return self.response
|
|
|
|
|
|
|
|
|
|
|
|
def main(broker_url):
|
|
|
|
connection = Connection(broker_url)
|
|
|
|
fibonacci_rpc = FibonacciRpcClient(connection)
|
|
|
|
print(' [x] Requesting fib(30)')
|
|
|
|
response = fibonacci_rpc.call(30)
|
2020-07-13 13:58:06 +00:00
|
|
|
print(f' [.] Got {response!r}')
|
2015-10-22 01:09:30 +00:00
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
main('pyamqp://')
|