- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我们有一个面向微服务的后端堆栈。所有构建在 Nancy
之上的微服务并使用 topshelf
注册为 Windows 服务.
处理大部分流量(~5000 请求/秒)的服务之一开始在 8 台服务器中的 3 台上出现线程池饥饿问题。
这是我们在到达特定端点时遇到的异常:
System.InvalidOperationException: There were not enough free threads in the ThreadPool to complete the operation.
at System.Net.HttpWebRequest.BeginGetResponse(AsyncCallback callback, Object state)
at System.Net.Http.HttpClientHandler.StartGettingResponse(RequestState state)
at System.Net.Http.HttpClientHandler.StartRequest(Object obj)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at RandomNamedClient.<GetProductBySkuAsync>d__20.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at ProductService.<GetBySkuAsync>d__3.MoveNext() in ...\ProductService.cs:line 34
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at ProductModule.<>c__DisplayClass15.<<.ctor>b__b>d__1d.MoveNext() in ...\ProductModule.cs:line 32
此端点调用另一个服务(不在我的团队的域内)以获取产品数据。实现如下:
Get["/product/sku/{sku}", true] = async (parameters, ctx) =>
{
string sku = parameters.sku;
var product = await productService.GetBySkuAsync(sku);
return Response.AsJson(new ProductRepresentation(product));
};
ProductService.GetBySkuAsync(string sku)
实现:
public async Task<Product> GetBySkuAsync(string sku)
{
var productDto = await randomNamedClient.GetProductBySkuAsync(sku);
if (productDto == null)
{
throw new ProductDtoNotFoundException("sku", sku);
}
var variantDto = productDto.VariantList.FirstOrDefault(v => v.Sku == sku);
if (variantDto == null)
{
throw new ProductVariantDtoNotFoundException("sku", sku);
}
return MapVariantDtoToProduct(variantDto, productDto);
}
RandomNamedClient.GetProductBySkuAsync(string sku)
实现(来自内部包):
public async Task<ProductDto> GetProductBySkuAsync(string sku)
{
HttpResponseMessage result = await this._serviceClient.GetAsync("Product?Sku=" + sku);
return result == null || result.StatusCode != HttpStatusCode.OK ? (ProductDto) null : this.Decompress<ProductDto>(result);
}
RandomNamedClient.Decompress<T>(HttpResponseMessage response)
实现:
private T Decompress<T>(HttpResponseMessage response)
{
if (!response.Content.Headers.ContentEncoding.Contains("gzip"))
return HttpContentExtensions.ReadAsAsync<T>(response.Content).Result;
using (GZipStream gzipStream = new GZipStream((Stream) new MemoryStream(response.Content.ReadAsByteArrayAsync().Result), CompressionMode.Decompress))
{
byte[] buffer = new byte[8192];
using (MemoryStream memoryStream = new MemoryStream())
{
int count;
do
{
count = gzipStream.Read(buffer, 0, 8192);
if (count > 0)
memoryStream.Write(buffer, 0, count);
}
while (count > 0);
return JsonConvert.DeserializeObject<T>(Encoding.UTF8.GetString(memoryStream.ToArray()));
}
}
}
我们所有的服务都构建为 Release/32 位。我们没有对线程池的使用做任何调整。
最佳答案
我在这段代码中看到的最大问题是 Decompress<T>
使用 Task.Result
阻止异步操作的方法.这可能会阻止当前正在处理线程池请求的线程的检索,或者更糟糕的是导致代码中的死锁(这正是您 shouldn't block on async code 的原因)。我不确定您是否看到这些请求得到了彻底处理,但如果 NancyFX 正在为您处理同步上下文的编码(看起来像 it does ),这很可能是线程池饥饿的根本原因。
您可以通过在该方法内进行所有 IO 处理来改变它 async
以及,并利用那些类已经公开的自然异步 API。或者,我绝对不建议这样做,您可以使用 ConfigureAwait(false)
无处不在。
(旁注 - 您可以使用 Stream.CopyToAsync()
简化代码)
正确的异步实现应该是这样的:
private async Task<T> DecompressAsync<T>(HttpResponseMessage response)
{
if (!response.Content.Headers.ContentEncoding.Contains("gzip"))
return await response.Content.ReadAsAsync<T>();
const int bufferSize = 8192;
using (GZipStream gzipStream = new GZipStream(
new MemoryStream(
await response.Content.ReadAsByteArrayAsync()),
CompressionMode.Decompress))
using (MemoryStream memoryStream = new MemoryStream())
{
await gzipStream.CopyToAsync(memoryStream, bufferSize);
return JsonConvert.DeserializeObject<T>(
Encoding.UTF8.GetString(memoryStream.ToArray()));
}
}
关于c# - HttpClient GetAsync 线程池饥饿,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35888198/
我看到很多人发布关于 NullInjectorError: No provider for HttpClient! 的问题但是我在 Karma 单元测试中遇到了更具描述性的错误。我一直在学习 Angu
全部, 我创造: public static final HttpClient DEFAULT_HTTPCLIENT = HttpClients .createDefault(); f
我正在使用 HttpClient fluent api 编写验收测试,但遇到了一些麻烦。 @When("^I submit delivery address and delivery time$")
有人可以分享如何配置现代 HttpClient 4.5.3 以重试失败的请求并在每次重试前等待一段时间吗? 到目前为止,我似乎正确理解了 .setRetryHandler(new DefaultHtt
我在使用 java 中的 HttpClient 库时遇到问题。 目标网站在 SSL ( https://www.betcris.com ) 上,我可以从该网站加载索引页面就好了。 但是,显示不同运动赔
所以我的应用涉及大量网络调用(可能连接到 10 个不同的服务器)和获取数据。从我读过的几篇文章中,建议重用 HTTPClient 实例,因为它可以防止资源(套接字等)的浪费。但是我发现围绕可扩展且健壮
我正在调用一个外部 API,并希望我的 API 可以进行单元测试。为此,我正在尝试包装 HttpClient。我现在只需要一种方法。 这是我的界面。 public interface IHttpCli
出于调试目的,我希望看到将要发送的原始请求。有没有一种方法可以直接从 HttpPost 或 HttpClient 的API中获得没有HTTP监视器的信息? 我发现了一些“几乎”重复的问题,但不是针对这
我正在尝试在小型 WebAssemply 应用程序(使用 .NET 5 创建)中测试 HttpClient。program.cs 包含以下语句来添加 HttpClient 服务: builder.Se
我在 Application_Start 事件中创建了 HttpClient 的单个实例,以便在 Global.asax.cs 中的应用程序中重用 应用程序启动中的代码: protected
我对此有点新手...基本上我需要运行一个脚本来从谷歌趋势下载.csv 文件。我按照这个reference写了下面的代码,代码如下: HttpClient client = new Defau
我正在尝试实现一个基本的 1 spout - 1 bolt Storm 拓扑。我有一个 Storm Bolt,可以使用 Apache HttpClient (4.3.1) 发出 HTTP 请求。但是,
我正在尝试在我的 Xamarin.Forms 移动应用程序中使用 HttpClient 创建网络服务层。 没有单例模式 单例模式 在第一种方法中,我在每个新请求中创建新的 http 客户端对象通过移动
在下面的示例中,我创建了一个 Java 11 httpClient,然后创建了多个并发 HttpRequest。 这是不好的做法吗? 每个 HttpRequest 都应该有自己的 HttpClient
我正在开发一个 Drupal 8 自定义模块。我在任何节点类型中都有两个字段(url 和文本 html 字段)。这是该模块所期望的功能: 该模块将抓取“url字段”的页面并复制html代码以将它们粘贴
我正在为 httpclient 使用 apache httpcompnonents 库。我想在多线程应用程序中使用它,其中线程数会非常高,并且会有频繁的 http 调用。这是我用来在执行调用后读取响应
最近我将我的代码库从 .net core 1.0 迁移到 2.0 。之后,我随机收到错误 “使用 System.Net.Http.HttpClient 时服务器返回无效或无法识别的响应错误”。我在 1
我有该代码: while(!lastPage && currentPage < maxPageSize){ StringBuilder request = new Strin
我的应用程序使用 Apache HTTPClient 4.3.5 发送 HTTP 请求并获得响应。 我想弄清楚应用程序收到了什么响应。 以下是日志片段- [Jan 04 2015 05:38:14.1
如何从 HttpClient 类型的现有对象获取 cookie? 我正在使用 HttpClient 版本 4.3.3,它不再有方法 httpClient.getCookieStore() 了。 最佳答
我是一名优秀的程序员,十分优秀!