为什么可能会从MySQLConnectionPool获得一个封闭连接?

2024-09-30 16:26:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我最近在mysql connector python模块中使用了MySQLConnectionPool,但对MySQLConnectionPool类中get\u connection方法的源代码有点怀疑。 get\ U连接方法的源代码如下:

    def get_connection(self):
        """Get a connection from the pool

        This method returns an PooledMySQLConnection instance which
        has a reference to the pool that created it, and the next available
        MySQL connection.

        When the MySQL connection is not connect, a reconnect is attempted.

        Raises PoolError on errors.

        Returns a PooledMySQLConnection instance.
        """
        with CONNECTION_POOL_LOCK:
            try:
                cnx = self._cnx_queue.get(block=False)
            except queue.Empty:
                raise errors.PoolError(
                    "Failed getting connection; pool exhausted")

            # pylint: disable=W0201,W0212
            if not cnx.is_connected() \
                    or self._config_version != cnx._pool_config_version:
                cnx.config(**self._cnx_config)
                try:
                    cnx.reconnect()
                except errors.InterfaceError:
                    # Failed to reconnect, give connection back to pool
                    self._queue_connection(cnx)
                    raise
                cnx._pool_config_version = self._config_version
            # pylint: enable=W0201,W0212

            return PooledMySQLConnection(self, cnx)

请注意,如果上面的条件“not cnx.is \u connected()”,似乎意味着从池中获取的连接可能已关闭。但是,当我了解并从mysqlconnection-close读取时,池中不可能有闭合连接

所以,我的疑问是,为什么上面的源代码中存在if条件'not cnx.is\u connected()'?或者为什么你可能会从游泳池得到一个封闭的连接


Tags: thetoselfconfigget源代码isversion