gpt4 book ai didi

c# - 在 .NET Core 2 中创建 HttpClient 的最佳实践

转载 作者:行者123 更新时间:2023-11-30 21:30:57 24 4
gpt4 key购买 nike

<分区>

让 HttpClientWrapper 在 .net core 2 中创建 HttpClients 是一个好习惯吗?

HttpClient 将被创建和缓存,然后从缓存中检索

    public class HttpClientWrapper : IHttpClientWrapper
{
private IMemoryCache cache;
public HttpClientWrapper(IMemoryCache _cache)
{
cache = _cache;
}

public HttpClient CreateClient(string baseUrl)
{
HttpClient httpClient;
if (!cache.TryGetValue(baseUrl, out httpClient))
{

MemoryCacheEntryOptions cacheExpirationOptions = new MemoryCacheEntryOptions();
//cacheExpirationOptions.AbsoluteExpiration = DateTime.Now.AddMinutes(30);
cacheExpirationOptions.SlidingExpiration = new TimeSpan(0, 30, 0);
cacheExpirationOptions.Priority = CacheItemPriority.Normal;


httpClient = new HttpClient();
httpClient.BaseAddress = new Uri(baseUrl);
cache.Set<HttpClient>(baseUrl, httpClient, cacheExpirationOptions);
}
return httpClient;
}
}

及其用法

[Route("api/[controller]")]
[ApiController]
public class CustomValuesController : ControllerBase
{
private readonly HttpClient httpClient;
private readonly HttpClient httpClient1;

public CustomValuesController(Common.IHttpClientWrapper _httpClientWrapper)
{
httpClient = _httpClientWrapper.CreateClient("http://localhost:9000");
httpClient1 = _httpClientWrapper.CreateClient("http://localhost:9001");
}
}

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com