-
RabbitMQ RPC(Remote procedure call)Cloud 2015. 3. 18. 09:00
예제소스rpc_server.py#!/usr/bin/env pythonimport pikaconnection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))channel = connection.channel()channel.queue_declare(queue='rpc_queue')def fib(n):if n == 0:return 0elif n == 1:return 1else:return fib(n-1) + fib(n-2)def on_request(ch, method, props, body):n = int(body)print " [.] fib(%s)" % (n,)response = fib(n)ch.basic_publish(exchange='',routing_key=props.reply_to,properties=pika.BasicProperties(correlation_id = \props.correlation_id),body=str(response))ch.basic_ack(delivery_tag = method.delivery_tag)channel.basic_qos(prefetch_count=1)channel.basic_consume(on_request, queue='rpc_queue')print " [x] Awaiting RPC requests"channel.start_consuming()rpc_client.py#!/usr/bin/env pythonimport pikaimport uuidclass 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.queueself.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 = bodydef call(self, n):self.response = Noneself.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=str(n))while self.response is None:self.connection.process_data_events()return int(self.response)fibonacci_rpc = FibonacciRpcClient()print " [x] Requesting fib(30)"response = fibonacci_rpc.call(30)print " [.] Got %r" % (response,)테스트 방법rpc 서버 실행python rpc_server.pyrpc 클라이언트 실행python rpc_client.py참고'Cloud' 카테고리의 다른 글
OpenStack 이미지 만들기 (0) 2015.03.23 OpenStack이 지원하는 하이퍼바이저 종류 (0) 2015.03.20 RabbitMQ 토픽 (0) 2015.03.17 RabbitMQ 라우팅 (0) 2015.03.16 RabbitMQ를 이용한 메세지 발행/구독 모델 (0) 2015.03.13 댓글