You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Psycopg3 AsyncConnectionPool使用Azure托管身份时令牌过期的连接刷新问题求助

Psycopg3 AsyncConnectionPool使用Azure托管身份时令牌过期的连接刷新问题求助

我现在用psycopg3初始化AsyncConnectionPool,Postgres数据库部署在Azure上,通过托管身份连接。我会从微软获取有效期1小时的令牌,初始化连接池和令牌有效期内的首次连接都正常,但令牌过期后需要建立新连接时,就会遇到这个错误:

error connecting in 'pool-1': connection failed: connection to server at "127.0.0.1", port 5433 failed: FATAL: The access token has expired. Please acquire a new token and retry.

我猜测是conninfo字符串被缓存起来了,但我需要每次建立新连接时都调用get_conninfo()来获取最新的令牌。有没有人知道该怎么解决这个问题?

以下是我的部分实现代码:

@classmethod
    async def connect(cls):
        """Initializes the connection pool."""
        async with cls._lock:
            if cls._instance is None:
                cls._instance = cls()
            if not hasattr(cls._instance, 'pool'):
                # Retrieve connection parameters
                cls._instance.user = settings.user
                cls._instance.host = settings.host
                cls._instance.port = settings.port
                cls._instance.dbname = settings.dbname
                cls._instance.connection_type = settings.connection_type

                if cls._instance.connection_type == "managed_identity":
                    cls._instance.credential = ManagedIdentityCredential()
                else:
                    cls._instance.password = settings.pgvector.pgvector_password.get_secret_value()

                cls._instance.pool = AsyncConnectionPool(
                        conninfo=await cls._instance.get_conninfo(),
                        open=True
                    )
                await cls._instance.pool.open()
                logger.info("Async database connection pool initialized in PostgresClient.")

    @classmethod
    async def get_conninfo(cls) -> str:
        """Returns connection info string based on the connection type."""
        if cls._instance.connection_type == "managed_identity":
            # retrieve token from Microsoft
            access_token = cls._instance.credential.get_token(
                "https://ossrdbms-aad.database.windows.net/.default"
            )
            return (
                f"dbname={cls._instance.dbname} host={cls._instance.host} "
                f"port={cls._instance.port} sslmode=require user={cls._instance.user} "
                f"password={access_token.token}"
            )
        else:
          ...

备注:内容来源于stack exchange,提问作者Tom

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 13:57:59