【发布时间】:2021-02-22 13:08:38
【问题描述】:
首先对不起我糟糕的英语:'(。
我正在开发一个客户端以将 POST 消息发送到托管在 Azure AppService 中的 WebAPI。我读到的最佳实践是使用单例模式,所以我是这样开发的。
公共静态类 UtilHTTP {
private static readonly ConcurrentDictionary<string, HttpClient> dicClient = new ConcurrentDictionary<string, HttpClient>();
public static string PostSingleton(string url, string contentType, string accept, string rq, Dictionary<string, string> headers)
{
Task<string> response = Fetch(url, contentType, accept, rq, headers);
response.Wait();
return response.Result;
}
private static HttpClient GetdicClient(string url, string contentType, string accept)
{
string key = string.Format("{0}#{1}#{2}", url, contentType, accept);
if (!dicClient.ContainsKey(key))
{
dicClient.GetOrAdd(key, new HttpClient());
if (!string.IsNullOrEmpty(accept))
{
dicClient[key].DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue(accept));
}
}
return dicClient[key];
}
private static async Task<string> Fetch(string url, string contentType, string accept, string rq, Dictionary<string, string> headers)
{
//_http.Timeout = new TimeSpan(0,0,6);
HttpContent content;
if (string.IsNullOrEmpty(contentType))
{
content = new StringContent(rq, Encoding.UTF8);
}
else
{
content = new StringContent(rq, Encoding.UTF8, contentType);
}
if (headers != null)
{
foreach (KeyValuePair<string, string> h in headers)
{
content.Headers.Add(h.Key, h.Value);
}
}
HttpResponseMessage response = await GetdicClient(url, contentType, accept).PostAsync(url, content);
string resultContent = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
{
resultContent = response.ReasonPhrase;
}
return resultContent;
}
}
我在 AppService 中有两个服务实例,但是所有请求都发往同一个实例,所以我无法扩展服务,性能也不是很好。
代码有问题吗?你认为是服务器端的问题吗?我必须使用其他模式吗?
非常感谢!
【问题讨论】:
标签: azure azure-web-app-service singleton httpclient webapi