Reputation: 15
This is the code from a official blog example app of tornado python framework. And one problem is confusing me: A MysqlDB connection is initialized as a gloal var in this application, but if high frequency request arrived, and the connection breaks off, so the whole app is down? why not initialize a new connection in each request handler? is it a better solution?
class Application(tornado.web.Application):
def __init__(self):
handlers = [
(r"/", HomeHandler),
(r"/archive", ArchiveHandler),
(r"/feed", FeedHandler),
(r"/entry/([^/]+)", EntryHandler),
(r"/compose", ComposeHandler),
(r"/auth/login", AuthLoginHandler),
(r"/auth/logout", AuthLogoutHandler),
]
settings = dict(
blog_title=u"Tornado Blog",
template_path=os.path.join(os.path.dirname(__file__), "templates"),
static_path=os.path.join(os.path.dirname(__file__), "static"),
ui_modules={"Entry": EntryModule},
xsrf_cookies=True,
cookie_secret="__TODO:_GENERATE_YOUR_OWN_RANDOM_VALUE_HERE__",
login_url="/auth/login",
debug=True,
)
tornado.web.Application.__init__(self, handlers, **settings)
# Have one global connection to the blog DB across all handlers
self.db = torndb.Connection(
host=options.mysql_host, database=options.mysql_database,
user=options.mysql_user, password=options.mysql_password)
Upvotes: 1
Views: 957
Reputation: 24007
A single MySQL connection for the whole application is the correct design here. If there is a network error, one request will get an exception, but the MySQL connection will reconnect for the next request and your application will recover. Built-in connection pooling allows your application to have several sockets connected to MySQL in order to await several MySQL operations at once.
If you create a new MySQL connection in each request handler you'll suffer the cost of setting up a TCP socket to MySQL for each HTTP request, as well as several network round-trips to log in to MySQL. Your performance will be much, much worse. If you measure it I expect you'll see that your request latency suffers badly if you create a new MySQL connection in each request handler.
Upvotes: 1