如何可靠地保持与我的Python Flask API打开的SSH隧道和MySQL连接?

我在Flask中构build了一个API,用Keras对文本信息进行分类。 我目前使用sshtunnelMySQLdb连接到MySQL数据库以从远程数据库获取消息。 整个应用程序被封装在一个Docker容器中。

我能够build立到远程数据库的连接并成功查询它,但是每当POST请求进入API时,我都会打开和closures一个新的ssh隧道,这会降低性能。

我试图打开一个单独的ssh隧道和数据库连接来“统治所有”,但是如果在一个小时左右之后没有任何活动,连接就会过时,然后API请求将永远耗费一天的时间来完成。

你是怎么做到的? 这是缓慢的不可避免的还是有办法定期刷新SSH和数据库连接?

这是我连接到我的数据库为每个传入的请求:

 with SSHTunnelForwarder( (host, 22), ssh_username=ssh_username, ssh_private_key=ssh_private_key, remote_bind_address=(localhost, 3306) ) as server: conn = db.connect(host=localhost, port=server.local_bind_port, user=user, passwd=password, db=database) 

好吧,我明白了。 我在这个答案中build议创build一个DB对象,但稍作修改。 我跟踪了与数据库连接的创build时间,然后每30分钟重新build立一次连接。 这意味着一个或两个查询花费的时间稍长一些,因为我正在重build与数据库的连接,但是其余部分的运行速度更快,连接也不会过时。

我已经在下面包含了一些代码。 我意识到代码并不完美,但是到目前为止,这是我的工作。

 import MySQLdb as mydb import time import pandas as pd from sshtunnel import SSHTunnelForwarder class DB: def __init__(self): self.open_ssh_tunnel() self.conn = None self.server = None self.connect() self.last_connected_time = time.time() def open_ssh_tunnel(self): connection_success = False while not connection_success: try: self.server = SSHTunnelForwarder( (host, 22), ssh_username=ssh_username, ssh_private_key=ssh_private_key, ssh_password=ssh_pwd, remote_bind_address=(localhost, 3306)) connection_success = True except: time.sleep(0.5) self.server.start() def connect(self): connection_success = False while not connection_success: try: self.conn = mydb.connect(host=localhost, port=server.local_bind_port, user=user, passwd=password, db=database) connection_success = True except: time.sleep(0.5) def query(self, sql): result = None current_time = time.time() if current_time - self.last_connected_time > 1600: self.last_connected_time = current_time self.server.close() self.conn.close() self.open_ssh_tunnel() self.connect() try: result = pd.read_sql_query(sql, self.conn).values self.conn.commit() except: self.server.close() self.conn.close() self.open_ssh_tunnel() self.connect() result = pd.read_sql_query(sql, self.conn).values return result