Tornado做鑑權服務性能實踐

一. Torado實現鑑權服務

使用python的第三方jwt做鑑權服務, 生產token代碼:

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;使用了自定義的對象倉儲,對比直接操作數據格式本身,這一點肯定是拖性能後退的
鑑權句柄的實現:

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服務和路由轉發:

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併發壓力,結果如下:

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章