c# – ASP .NET Core 2.1-preview2 HttpClient死锁
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – ASP .NET Core 2.1-preview2 HttpClient死锁,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含4114字,纯文字阅读大概需要6分钟。
内容图文
![c# – ASP .NET Core 2.1-preview2 HttpClient死锁](/upload/InfoBanner/zyjiaocheng/789/abae4e66d0084c8fb0c3c7f23e2ff0d0.jpg)
我在Azure Web应用程序上托管了ASP.NET Core 2.1应用程序.我通过WebSockets发送照片base64字符串,然后通过HttpClient发送到Azure Face API.
在大约150-250个请求后,HttpClient停止响应,我不能在我的应用程序的任何部分使用HttpClient类.
在我的localhost它工作正常,我从来没有遇到这个问题.
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服务中调用:
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)在localhost环境中它有效.我运行了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);
});
这将允许键入的客户端不必为每个调用添加密钥
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死锁全部内容,希望文章能够帮你解决c# – ASP .NET Core 2.1-preview2 HttpClient死锁所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。