我用django构建了一个web服务器。在
并使用一个线程来运行任务,该任务将客户机发送的数据保存到数据库中。在
while True: ... try: self.dbTarget, created = ClientMonitor.objects.get_or_create(Machine_code=own_MachC) data = self.workQueue.get() #from client sent self.dbTarget.setValue(data) #Custom method assigning self.dbTarget.save() #django ORM except InterfaceError as ee: pass
线程是长时间运行的,但是很长一段时间后会出现接口错误,因为mysql服务器断开连接,超时8小时。在
Especially it can not auto-reconnect to the db. Creating a new thread will be OK, but it will increase resource occupation.
所以当连接在同一线程中关闭时,我想重新连接db。另外,Django每个请求都会得到一个新的连接。在
如何在同一线程中重新连接到数据库? 谢谢您!!!在
Django本身使用函数^{} 在每个请求的开始和结束时关闭超过其生存期的任何连接。这将检测连接是否早于数据库设置中指定的
MAX_AGE
,或者是否不可用。如果将MAX_AGE
设置为低于数据库的超时值,则不会因为db超时而遇到InterfaceError
。在只需关闭异常处理程序中的连接。下次应用程序尝试与数据库通信时,应建立新的连接:
相关问题 更多 >
编程相关推荐