YorkCai 2019-06-29
使用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内存,没有反向代理和缓存的前提下,性能表现如下
使用jmeter做200并发压力,结果如下:
最大时延4s,TPS达到39.6/s,感觉还是很理想的
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()
性能有明显提升:
最大时延484ms,TPS达到了126