I. Torado implements authentication services

Use third party JWT of Python as authentication service to produce token code:

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 version 3.6 uses PyMongo for database operations; The use of custom object repositories, as opposed to directly manipulating the data format itself, is definitely an implementation of the authentication handle that drags performance back:

class AuthHandle(RequestHandler):

    def post(self):
            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:

Tornado does web services and routing forwarding:

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"))

Performance optimization practice

Using CENOS environment, dual core, 8GB of memory, no reverse proxy and cache, the performance is as follows

2.1 Pressure test

Using JMeter to do 200 concurrent pressure, the results are as follows:

The maximum delay is 4S and TPS reaches 39.6/s, which feels very ideal

2.2 After starting multiple processes

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) # process number is equal to the number machine nuclear tornado. Ioloop. Ioloop. The instance (). The start ()

Significant performance improvement:

The maximum delay is 484ms and the TPS reaches 126