gpt4 book ai didi

c# - ASP .NET Core 2.1-preview2 HttpClient 死锁

转载 作者:太空狗 更新时间:2023-10-30 01:29:45 24 4
gpt4 key购买 nike

我在 Azure Web 应用程序上托管了 ASP.NET Core 2.1 应用程序。我通过 WebSockets 发送照片 base64 字符串,然后通过 HttpClient 发送到 Azure Face API。

在大约 150-250 个请求后,HttpClient 停止响应,我无法在我的应用程序的任何部分使用 HttpClient 类。

在我的本地主机上它工作正常,我从来没有遇到过这个问题。

public class FaceApiHttpClient
{
private HttpClient _client;

public FaceApiHttpClient(HttpClient client)
{
_client = client;
}

public async Task<string> GetStringAsync(byte[] byteData,string uri)
{
using (ByteArrayContent content = new ByteArrayContent(byteData))
{
content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

HttpResponseMessage response = await _client.PostAsync(uri, content).ConfigureAwait(false);

return await response.Content.ReadAsStringAsync().ConfigureAwait(false);
}

}
}

DI:

         services.AddHttpClient<FaceApiHttpClient>(
client => {
client.BaseAddress = new Uri("xxx");
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "xxx");
});

FaceApiClient 的方法在 Scoped Service 中调用:

public interface IFaceAPIService
{
Task<DataServiceResult<List<Face>>> GetFacesDataFromImage(byte[] byteArray);
}

public class FaceAPIService: ServiceBase, IFaceAPIService
{
private readonly IServerLogger _serverLogger;
private FaceApiHttpClient _httpClient;
//Consts
public const string _APIKey = "xxx";
public const string _BaseURL = "xxx";

public FaceAPIService(IServerLogger serverLogger, FaceApiHttpClient client)
{
_serverLogger = serverLogger;
_httpClient = client;
}

public async Task<DataServiceResult<List<Face>>> GetFacesDataFromImage(byte[] byteData)
{
try
{
// Request parameters. A third optional parameter is "details".
string requestParameters = "returnFaceId=true&returnFaceLandmarks=false&returnFaceAttributes=age,gender,headPose,smile,facialHair,glasses,emotion,hair,makeup,occlusion,accessories,blur,exposure,noise";

// Assemble the URI for the REST API Call.
string uri = _BaseURL + "/detect" + "?" + requestParameters;
var result = await _httpClient.GetStringAsync(byteData, uri).ConfigureAwait(false);
List<Face> faces = JsonConvert.DeserializeObject<List<Face>>(result);
return Success(faces);

}
catch (Exception ex)
{
_serverLogger.LogExceptionFromService(ex);
return DataServiceResult.ErrorResult<List<Face>>(ex.Message);
}
}
}

a) 在本地主机环境中它可以工作。我运行 11 个模拟器,每秒有很多请求,而且它从未中断(10 个小时的模拟器,超过 20k 个请求)。

b) HttpClient 停止在应用程序的任何部分工作,而不仅仅是在一个类中。

如何解决这个问题?

最佳答案

考虑稍微改变一下设计。

使用类型化客户端的假设是它的配置不会经常更改,并且应该在注册类型化客户端时添加一次。

services.AddHttpClient<FaceApiHttpClient>(_ => {
_.BaseAddress = new Uri(Configuration["OcpApimBaseURL"]);
var apiKey = Configuration["OcpApimSubscriptionKey"];
_.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", apiKey);
_.Timeout = new TimeSpan(0, 0, 10);
});

这将允许键入的客户端不必为每次调用添加 key

public class FaceApiHttpClient {
private readonly HttpClient client;

public FaceApiHttpClient(HttpClient client) {
this.client = client;
}

public async Task<string> GetStringAsync(byte[] byteData, string uri) {
using (var content = new ByteArrayContent(byteData)) {
// This example uses content type "application/octet-stream".
// The other content types you can use are "application/json" and "multipart/form-data".
content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

// Execute the REST API call.
HttpResponseMessage response; response = await _client.PostAsync(uri, content).ConfigureAwait(false);

// Get the JSON response.
return await response.Content.ReadAsStringAsync().ConfigureAwait(false);
}
}
}

需要注意的是ASP.NET Core 2.1-preview1: Introducing HTTPClient factory

A typed client is, effectively, a transient service, meaning that a new instance is created each time one is needed and it will receive a new HttpClient instance each time it is constructed. This means that the configuration func, in this case retrieving the URI from configuration, will run every time something needs a FaceApiHttpClient.

根据以前的文档,创建那么多客户端会带来问题,但这里的假设是此新功能的开发人员在设计时考虑到了这一点。

之所以这样说,是因为您描述的问题与之前的问题相似,原因相同。

关于c# - ASP .NET Core 2.1-preview2 HttpClient 死锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49831568/

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