连接重用可以做什么?

what can be done for connection re use?

我正在使用 azure postgres sql,其中我有一种常用方法可以给我连接字符串,

protected readonly string databaseConnString = "Host={0}.postgres.database.azure.com;Username={1}@{2};Password={3};DB={4};Ssl Mode=Require";
    

 protected virtual async Task<NpgsqlConnection> GetDBConnection()
    {
        var connString = string.Empty;
        NpgsqlConnection conn;

        try
        {
            //certificate check
            conn = new NpgsqlConnection(databaseConnString);

            try
            {
                //open the connection
                await conn.OpenAsync();
            }
            catch (PostgresException ex)
            {
                
            }
            finally
            {
                //close the connection
                await conn.CloseAsync();
            }
        }
        
        //return connection string
        return conn;
    }

当我再次使用 open/close 连接时,我在应用程序的任何地方都在使用上面的连接字符串,

   using (var conn = await GetDBConnection())
        {
          await conn.OpenAsync();
          //do the work
          await conn.CloseAsync();
        }

我正在使用 npgsql .net core library,后来发现 PgBouncer 在这里无济于事。如何最小化连接open/close并能实现连接池?

Pooling 由连接字符串中的 Pooling=true 控制,但默认情况下它是打开的。

  • 当您调用 NpgsqlConnectiona.Open 时,物理连接将从池中获取(如果存在),您无需执行任何操作。

  • 处理 NpgsqlConnection时,它将返回到池中以供重复使用。

默认情况下,您无需做任何事情或担心。

Pooling Documentation