码迷,mamicode.com
首页 > Web开发 > 详细

tornado+jsonrpc

时间:2018-10-08 13:00:51      阅读:220      评论:0      收藏:0      [点我收藏+]

标签:tornado   col   style   接口   tps   syn   soc   handle   .com   

rpc:远程过程调用(A服务调用B服务的一个方法或函数)

技术分享图片

技术分享图片

 

tornado中jsonrpc的使用

import tornado.httpserver
import tornado.ioloop
import tornado.web
from jsonrpcserver.aio import methods

#第一个方法
@methods.add
async def ping(context, **kwargs):
    return kwargs

#第二个方法
@methods.add
async def ping_one(context, **kwargs):
    print(‘ping one‘)
    return kwargs


class 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 time

from jsonrpcclient import HTTPClient

req = 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

标签:tornado   col   style   接口   tps   syn   soc   handle   .com   

原文地址:https://www.cnblogs.com/rgcLOVEyaya/p/RGC_LOVE_YAYA_692days_820.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!