Django+Pika RPC长期闲置丢失Postgres连接问题求助
问题:Django+Pika RPC长期闲置后丢失Postgres连接,触发psycopg.OperationalError
psycopg.OperationalError: consuming input failed: server closed the connection unexpectedly
使用Django结合Pika实现RPC逻辑,以RabbitMQ作为消息中间件,服务长期闲置后会丢失数据库连接,后续请求触发上述错误。经排查判断问题根源为长时间闲置的线程导致数据库连接被Postgres主动终止,与RabbitMQ无关。
已尝试的解决方案
- 强制重新打开数据库连接:
django.db.connection.connect()
- 在RPC请求执行前后关闭所有数据库连接:
def close_database(message: str) -> None: print(f"Attempting to close database connections: {message}") for connection in connections.all(): try: connection.close() print(f"Closed connection: {message}") except InterfaceError: pass except DatabaseError as exc: str_exc = str(exc) if "closed" not in str_exc and "not connected" not in str_exc: print(f"Error closing connection: {exc}") def handle_rpc_request(routing_key: str, data: dict[str, Any]) -> Optional[str]: """Handle an RPC request.""" print(f"External message received in Pulse - {routing_key}") close_database("before RPC request") try: response = celery_pubsub.publish_now(routing_key, data) finally: close_database("after RPC request")
以上两种方案均未能解决问题。
技术栈
- Django 5.1(启用数据库连接池)
- GCP托管PostgreSQL + Cloud Run
- RabbitMQ
求助内容
- 还有哪些方法可以尝试解决数据库连接丢失问题?
- 若暂时无法解决,如何快速复现该问题以缩短验证周期?
内容的提问来源于stack exchange,提问作者David Sigley
相关产品推荐
相关产品推荐

