Cloud Run连接Cloud SQL Postgres时间歇性出现pg8000.InterfaceError
间歇性pg8000.exceptions.InterfaceError问题排查求助
- 从Cloud Run连接Cloud SQL托管的PostgreSQL 11时,间歇性出现pg8000.exceptions.InterfaceError错误
- 错误频率:每2-5天发生1-2次
- 部署环境:公网,未使用私有VPC
- 技术栈:Python 3.7 + PostgreSQL 11
- 容器状态:新容器启动前CPU、内存使用率稳定在60%左右
- 连接池状态:未发现数据库或容器连接池耗尽情况
以下是使用Google连接器管理数据库连接池的代码:
class DatabaseConnection: _instance = None pool: Engine = None def __new__(cls): if cls._instance is None: cls._instance = super(DatabaseConnection, cls).__new__(cls) return cls._instance @classmethod def initialize_pool(cls): if cls.pool is None: try: settings = Settings() # Initialize Cloud SQL Connector connector = Connector() def getconn() -> pg8000.dbapi.Connection: # Use the connector for Cloud SQL return connector.connect( settings.DB_CONNECTION_NAME, "pg8000", user=settings.DB_USER, password=settings.DB_PASSWORD, db=settings.DB_NAME, ip_type=IPTypes.PUBLIC, ) # Use 'creator' to integrate Cloud SQL Connector with SQLAlchemy cls.pool = create_engine( "postgresql+pg8000://", creator=getconn, pool_size=10, max_overflow=1, pool_timeout=30, pool_recycle=1080, pool_pre_ping=True, ) print("Database pool initialized") except Exception as e: print("Failed to initialize database pool") traceback.print_exc() @classmethod def dispose_pool(cls): if cls.pool is not None: cls.pool.dispose() cls.pool = None print("Database pool disposed") def get_connection(self): if self.pool: return self.pool.connect() raise SQLAlchemyError("Database pool not initialized")
FastAPI启动/关闭时初始化/销毁连接池:
@app.on_event("startup") async def startup_event(): # Initialize the database connection pool DatabaseConnection.initialize_pool() @app.on_event("shutdown") async def shutdown_event(): # Dispose of the database connection pool DatabaseConnection.dispose_pool()
路由中调用连接的示例:
with DatabaseConnection().get_connection() as postgre_db_connection: query_string = text( "SELECT * FROM public.brand_data" ) res = postgre_db_connection.execute(query_string) query_result_single_row = res.fetchone()
尽管已排查上述状态,但错误的随机性导致复现困难,调试受阻。求有类似经验或相关专业知识的人提供排查思路和解决建议,如需更多日志或细节可随时补充。
内容的提问来源于stack exchange,提问作者doomsday
相关产品推荐
相关产品推荐

