You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Ocelot v17.0.1负载均衡遇HttpClient超时及ResponderMiddleware错误求助

Ocelot v17.0.1负载均衡超时异常求助

遇到以下超时异常:

The request was canceled due to the configured HttpClient.Timeout of 90 seconds elapsed. errors found in ResponderMiddleware.

已知Ocelot默认超时为90秒,已查阅官方文档及同类ResponderMiddleware错误案例,未找到匹配场景。以下是相关配置及代码,求问是否有同类问题、问题原因及解决建议:

配置文件

{
  "Routes": [
    {
      "DownstreamPathTemplate": "/{everything}",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "192.xxx.xxx.xxx",
          "Port": xxxxx
        },
        {
          "Host": "192.xxx.xxx.xxx",
          "Port": xxxxx
        },
        {
          "Host": "192.xxx.xxx.xxx",
          "Port": xxxxx
        }
      ],
      "UpstreamPathTemplate": "/{everything}",
      "LoadBalancerOptions": {
        "Type": "LeastConnection"
      },
      "UpstreamHttpMethod": [ "GET", "POST" ]
    }
  ],
  "GlobalConfiguration": {
    "RequestIdKey": "OcRequestId",
    "AdministrationPath": "/administration"
  }
}

Startup.cs配置

services.AddHttpClient("Client", c =>
{
    c.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    c.Timeout = TimeSpan.FromMinutes(1);
})
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler()
{
    ServerCertificateCustomValidationCallback = (m, crt, chn, e) => true
});

services.AddScoped<ITypedClient, TypedClient>();

ClientApp代码

private ITypedClient _httpClient { get; set; }

public ClientApp(ITypedClient httpClient)
{
    _httpClient = httpClient;
}


public List<Model> GetEmployee()
{
    var result = _client.GetReq("/employee");
    
    return result;
}

可能的问题原因

  • Ocelot默认会创建独立的HttpClient实例,你手动注册的"Client"命名客户端并未被Ocelot使用,因此你的1分钟超时配置不生效,Ocelot仍用默认90秒超时。
  • 下游服务的/employee接口响应速度慢,单请求耗时超过90秒,触发超时。
  • LeastConnection负载均衡策略选中的节点恰好是性能较差的节点,持续出现超时。

解决建议

  1. 配置Ocelot下游请求超时:在路由配置中添加DownstreamRequestTimeout字段,覆盖默认90秒,比如设置为1分钟(60000毫秒):
"Routes": [
  {
    // 原有配置不变
    "DownstreamRequestTimeout": 60000
  }
]
  1. 让Ocelot使用自定义HttpClient:在Ocelot初始化时直接配置其使用的HttpClient,确保超时等配置生效:
services.AddOcelot()
    .ConfigureHttpClient(client => 
    {
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        client.Timeout = TimeSpan.FromMinutes(1);
    })
    .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler()
    {
        ServerCertificateCustomValidationCallback = (m, crt, chn, e) => true
    });
  1. 排查下游服务性能:检查三个下游节点的/employee接口响应时间,定位是否存在节点性能瓶颈,针对性优化下游服务。
  2. 调整负载均衡策略:暂时切换为RoundRobin策略,验证是否是LeastConnection选中慢节点导致的问题,再做后续调整。

内容的提问来源于stack exchange,提问作者Riyan Afriyanto

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 08:05:26