using Newtonsoft.Json;
using System.Collections.Concurrent;
using System.Net;
using System.Text;
using AmrControl.Common.HttpClients;
namespace AmrControl.Common.HttpClients
{
///
/// 请求客户端
///
public class DefaultHttpClient
{
///
/// 用于加锁,防止对象重复构建
///
private static object lockObj = new Object();
///
/// httpClient,用于http访问
///
private readonly HttpClient _httpClient;
///
/// get客户端
///
private readonly HttpGet httpGet;
///
/// post客户端
///
private readonly HttpPost httpPost;
///
/// put操作客户端
///
private readonly HttpPut httpPut;
///
/// delete客户端
///
private readonly HttpDelete httpDelete;
///
/// 地址终端维护
///
private static volatile ConcurrentDictionary clients = new();
//域名+地址,如http://127.0.0.1:5089/
private readonly string baseUri;
///
/// 私有化构造方法
///
private DefaultHttpClient(string hostAddr)
{
var socketsHttpHandler = new SocketsHttpHandler()
{
//每个请求最大连接数
MaxConnectionsPerServer = 128,
//连接池中TCP连接最多可以闲置多久,设置180秒超时回收
PooledConnectionIdleTimeout = TimeSpan.FromSeconds(180),
//连接超时,默认60s
ConnectTimeout = TimeSpan.FromSeconds(60),
// http响应头最大字节数(单位:KB)
MaxResponseHeadersLength = 128,
//启用压缩
AutomaticDecompression = DecompressionMethods.GZip,
};
_httpClient = new(socketsHttpHandler)
{
//等待响应超时时间,默认:100秒。
Timeout = TimeSpan.FromSeconds(60)
};
this.baseUri = hostAddr;
this.httpGet = new HttpGet(_httpClient, hostAddr);
this.httpPost = new HttpPost(_httpClient, hostAddr);
this.httpPut = new HttpPut(_httpClient, hostAddr);
this.httpDelete = new HttpDelete(_httpClient, hostAddr);
}
///
/// 获取httpGet客户端
///
///
public HttpGet httpGetClient()
{
return httpGet;
}
///
/// 获取httpPost客户端
///
///
public HttpPost httpPostClient()
{
return httpPost;
}
///
/// 获取httpPut客户端
///
///
public HttpPut httpPutClient()
{
return httpPut;
}
///
/// 获取httpDelete客户端
///
///
public HttpDelete httpDeleteClient()
{
return httpDelete;
}
///
/// 获取客户端
///
///
public static DefaultHttpClient getClient(string baseUri)
{
if (!clients.ContainsKey(baseUri) || clients[baseUri] == null)
{
//尝试获取锁
lock (lockObj)
{
//再次校验,防止重复构建
if (!clients.ContainsKey(baseUri) || clients[baseUri] == null)
{
clients[baseUri] = new DefaultHttpClient(baseUri);
}
}
}
return clients[baseUri];
}
}
}