【发布时间】:2018-12-22 11:09:26
【问题描述】:
让 HttpClientWrapper 在 .net core 2 中创建 HttpClients 是一种好习惯吗?
HttpClients 将被创建和缓存,然后从缓存中检索
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");
}
}
【问题讨论】:
标签: c# asp.net-core httpclient