zoukankan      html  css  js  c++  java
  • tornado+jsonrpc

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

    tornado中jsonrpc的使用

    import json
    
    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):
        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(json.dumps(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)
    # 批量请求两个方法
    res = req.send('''[{"jsonrpc": "2.0", "method": "ping_one", "params": {"name": 351}, "id": 21},
                       {"jsonrpc": "2.0", "method": "ping_one", "params": {"name": 352}, "id": 22}
                       ]''')
    print(res)

     服务端响应如下:

    客户端响应如下:

    json-rpc是一种非常轻量级的跨语言远程调用协议,实现及使用简单。方便语言扩展客户端的实现。

    使用场景:

    调用另一个服务的某个方法,相对于接口调用,在代码整洁及解耦方面有优势。并且可以使用批量请求(在所有请求完成后,在一并返回)

    并且如果是 频繁请求另一个服务的某种功能,使用rpc比http较为轻量级,并且结合socket使用,达到一个连接中多个请求,减少系统开销

    相关网址:https://www.zybuluo.com/phper/note/76641

                      https://blog.csdn.net/red_heel/article/details/78911252

                      https://www.cnblogs.com/chunguang/p/5724782.html

  • 相关阅读:
    CSS去掉 a 标签点击后出现的虚线框
    AMD 和 CMD的区别
    sublime text常用快捷键
    jsonp详解
    JSON详解
    JS知识总结
    input 单选按钮radio 取消选中(转载)
    koala 编译scss不支持中文解决方案
    Spring事务的传播行为 @Transactional(转)
    Ubuntu下JDK+Tomcat+MySql环境的搭建
  • 原文地址:https://www.cnblogs.com/rgcLOVEyaya/p/RGC_LOVE_YAYA_692days_820.html
Copyright © 2011-2022 走看看