rabbitmq python rpc_利用RabbitMQ实现RPC(python)

原标题:利用RabbitMQ实现RPC(python)

RPC——远程过程调用,通过网络调用运行在另一台计算机上的程序的函数\方法,是构建分布式程序的一种方式。RabbitMQ是一个消息队列系统,可以在程序之间收发消息。利用RabbitMQ可以实现RPC。本文所有操作都是在CentOS7.3上进行的,示例代码语言为Python。

RabbiMQ以及pika模块安装

yum install rabbitmq-server python-pika -y

systemctl start rabbitmq-server

RPC的基本实现

RPC的服务端代码如下:

#!/usr/bin/env python

importpika

connection =pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))

channel =connection.channel()

channel.queue_declare(queue='rpc_queue')

deffun(n):

return2*n

defon_request(ch, method, props, body):

n =int(body)

response = fun(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()

以上代码中,首先与RabbitMQ服务建立连接,然后定义了一个函数fun(),fun()功能很简单,输入一个数然后返回该数的两倍,这个函数就是我们要远程调用的函数。on_request()是一个回调函数,它作为参数传递给了basic_consume(),当basic_consume()在队列中消费1条消息时,on_request()就会被调用,on_request()从消息内容body中获取数字,并传给fun()进行计算,并将返回值作为消息内容发给调用方指定的接收队列,队列名称保存在变量props.reply_to中。

RPC的客户端代码如下:

#!/usr/bin/env python

importpika

importuuid

classRpcClient(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)

defon_response(self,ch, method, props, body):

ifself.corr_id==props.correlation_id:

self.response= body

defcall(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=str(n))

whileself.responseisNone:

self.connection.process_data_events()

returnstr(self.response)

rpc=RpcClient()

print(" [x] Requesting")

response =rpc.call(2)

print(" [.] Got %r"% response)

代码开始也是连接RabbitMQ,然后开始消费消息队列callback_queue中的消息,该队列的名字通过Request的属性reply_to传递给服务端,就是在上面介绍服务端代码时提到过的props.reply_to,作用是告诉服务端把结果发到这个队列。basic_consume()的回调函数变成了on_response(),这个函数从callback_queue的消息内容中获取返回结果。

函数call实际发起请求,把数字n发给服务端程序,当response不为空时,返回response值。

下面看运行效果,先启动服务端:

30f45dcf5c42ae0228bed758aa22049f.png

在另一个窗口中运行客户端:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值