是否可以为 HTTP 客户端池设置最小连接数?

问题描述 投票:0回答:1

我想知道是否可以以某种方式指定系统将努力持续维护的池的最小连接数?

对于连接限制,我使用 MaxConnectionsPerServer 属性,它工作正常,但我找不到像 MinConnectionsPerServer 这样的东西

这里是一个代码片段,以便更好地理解:

services.AddHttpClient<HttpClient>()
      .ConfigurePrimaryHttpMessageHandler(() => new SocketsHttpHandler
      {
        ConnectTimeout = TimeSpan.FromSeconds(2),
    MaxConnectionsPerServer = 100,
    PooledConnectionLifetime = TimeSpan.FromMilliseconds(-1),
    PooledConnectionIdleTimeout = TimeSpan.FromMilliseconds(-1)
      })
      .SetHandlerLifetime(TimeSpan.FromMilliseconds(-1));

提前致谢!

c# http pool
1个回答
0
投票

在标准 .NET HttpClient 实现中,没有像 MinConnectionsPerServer 这样的内置属性允许您指定系统将努力持续维护的最小连接数。但是,您可以通过自己主动创建和管理连接池来实现类似的行为。 一种方法是创建 HttpClient 的自定义实现,在其中显式管理连接池。以下是如何实现此目标的简化示例: 公共类 CustomHttpClient : HttpClient { 私有只读 SemaphoreSlim _connectionPool;私有只读 Uri _base地址; 公共 CustomHttpClient(Uri baseAddress, int minConnections, int maxConnections) { _connectionPool = 新 SemaphoreSlim(maxConnections); _baseAddress = 基地址; ServicePointManager.FindServicePoint(_baseAddress).ConnectionLimit = maxConnections;

   // Initialize the connection pool with minimum connections
   for (int i = 0; i < minConnections; i++)
   {
       _connectionPool.Release();
   }    }
   public async Task<HttpResponseMessage> SendAsyncWithPooling(HttpRequestMessage request)    {
   await _connectionPool.WaitAsync();
   
   try
   {
       return await SendAsync(request);
   }
   finally
   {
       _connectionPool.Release();
   }    } }
 //  Then, you can use this CustomHttpClient in your code instead of the    standard HttpClient:
   var customClient = new CustomHttpClient(baseAddress, minConnections:    5, maxConnections: 100);
© www.soinside.com 2019 - 2024. All rights reserved.