Tornado作鉴权服务性能实践

一. Torado实现鉴权服务

使用python的第三方jwt作鉴权服务, 生产token代码:python

def create_token(self, userId, product, level):
    payload = {
        "product": product,
        "level": level,
        "exp": int(time.time()) + 86400 * 7,
        "username": userId,
    }
    token = jwt.encode(payload, SECRETKEY, algorithm='HS256')
    return token

mongodb版本是3.6,数据库操做使用了pymongo;使用了自定义的对象仓储,对比直接操做数据格式自己,这一点确定是拖性能后退的
鉴权句柄的实现:web

class AuthHandle(RequestHandler):

    def post(self):
        try:
            body = json.loads(self.request.body)
            user = UserRepository().get(body['username'])
            if not user:
                user = UserRepository().create_new(body['username'])
            token = Authenticationner().create_token(user.userId, user.product, user.level)
            self.write({'token': token})
        except Exception:
            Logger.error(traceback.format_exc())

tornado作web服务和路由转发:mongodb

class Application(Application):

    def __init__(self):
        handlers = [
            (r"/users/login", AuthHandle),
        ]
        super(Application, self).__init__(handlers, **settings)

if __name__ == "__main__":
    application = Application()
    application.listen(address.get("port"), address.get("ip"))
    tornado.ioloop.IOLoop.instance().start()

二. 性能优化实践

使用cenos环境,双核,8G内存,没有反向代理和缓存的前提下,性能表现以下数据库

2.1 压力测试

使用jmeter作200并发压力,结果以下:json

clipboard.png

最大时延4s,TPS达到39.6/s,感受仍是很理想的缓存

2.2 开启多进程以后

from tornado.options import options, define

application = Application()
define("port", default=address.get("port"), help="", type=int)
http_server = tornado.httpserver.HTTPServer(application)
http_server.bind(options.port, address.get("ip"))
http_server.start(0)  # 进程数量等于机器核数量
tornado.ioloop.IOLoop.instance().start()

性能有明显提高:性能优化

clipboard.png

最大时延484ms,TPS达到了126并发

相关文章
相关标签/搜索