Skip to content

Instantly share code, notes, and snippets.

@joastbg
Created August 4, 2016 09:13
Show Gist options
  • Save joastbg/54b3f7d4b6aa276a57e396836e565a4e to your computer and use it in GitHub Desktop.
Save joastbg/54b3f7d4b6aa276a57e396836e565a4e to your computer and use it in GitHub Desktop.
RPC - RabbitMQ + Protobuf
#!/usr/bin/env python
import pika
import uuid
import json
import sample2_pb2 as sample2
import base64
person = sample2.Person()
person.name = "Johan Astborg"
person.id = 1001
person.email = "[email protected]"
print person
class FibonacciRpcClient(object):
def __init__(self):
self.connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
self.channel = self.connection.channel()
result = self.channel.queue_declare(exclusive=True)
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):
if self.corr_id == props.correlation_id:
self.response = body
def call(self, n):
self.response = None
self.corr_id = str(uuid.uuid4())
self.channel.basic_publish(exchange='',
routing_key='rpc_queue',
properties=pika.BasicProperties(
reply_to = self.callback_queue,
correlation_id = self.corr_id,),
body=base64.b64encode(person.SerializeToString()))
while self.response is None:
self.connection.process_data_events()
person2 = sample2.Person()
person2.ParseFromString(base64.b64decode(self.response))
return str(person2)
fibonacci_rpc = FibonacciRpcClient()
print(" [x] Requesting json")
response = fibonacci_rpc.call(json.dumps({'_id': 1001, 'type': 'products', 'query': 'all', 'limit': 100, 'offset': 0}))
print "------"
print response
print "------"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment