rpc:远程过程调用(A服务调用B服务的一个方法或函数)
tornado中jsonrpc的使用
import tornado.httpserverimport tornado.ioloopimport tornado.webfrom jsonrpcserver.aio import methods#第一个方法@methods.addasync def ping(context, **kwargs): ???return kwargs#第二个方法@methods.addasync def ping_one(context, **kwargs): ???print(‘ping one‘) ???return kwargsclass RpcHandler(tornado.web.RequestHandler): ???def get(self): ???????response = methods.dispatch({"jsonrpc": "2.0", "method": "ping", "id": 33, ‘params‘: {‘where‘: 23}}, ???????????????????????????????????context={‘name‘: ‘张三‘}) ???????if not response.is_notification: ???????????self.write(response) ???????#通过此接口调用不同的方法 ???async def post(self): ???????rpc_request = self.request.body.decode() ???????response = await methods.dispatch(rpc_request, context={‘key‘: ‘one‘}) ???????if not response.is_notification: ???????????self.write(response)def make_app(): ???settings = {‘debug‘: True} ???return tornado.web.Application([ ???????(r‘/‘, RpcHandler), ???], **settings)if __name__ == ‘__main__‘: ???app = make_app() ???http_server = tornado.httpserver.HTTPServer(app) ???ip = ‘127.0.0.1‘ ???port = 8000 ???http_server.bind(8000, ip) ???http_server.start(1) ???print(‘server start! http://{}:{}‘.format(ip, port)) ???tornado.ioloop.IOLoop.current().start()
客户端调用代码如下:
import timefrom jsonrpcclient import HTTPClientreq = HTTPClient(‘http://127.0.0.1:8000/‘)# 请求ping方法res = req.request(‘ping‘, name=34)print(res)time.sleep(1)# 请求ping_one方法res = req.request(‘ping_one‘, name=35)print(res)time.sleep(1)
服务端响应如下:
客户端响应如下:
json-rpc是一种非常轻量级的跨语言远程调用协议,实现及使用简单。方便语言扩展客户端的实现。
使用场景:
调用另一个服务的某个方法,相对于接口调用,在代码整洁及解耦方面有优势。
并且如果是 频繁请求另一个服务的某种功能,使用rpc比http较为轻量级,并且结合socket使用,达到一个连接中多个请求,减少系统开销
相关网址:https://www.zybuluo.com/phper/note/76641
https://blog.csdn.net/red_heel/article/details/78911252
tornado+jsonrpc
原文地址:https://www.cnblogs.com/rgcLOVEyaya/p/RGC_LOVE_YAYA_692days_820.html