当主主机在 Ocelot API 网关(C#、.NET Core、Ocelot)中不可用时重定向到辅助主机

问题描述 投票:0回答:1

我想使用 Ocelot API Gateway 来连接服务,但如果主主机不可用,则需要重定向到辅助主机。

例如,在下面的配置中,我有两个端口,一个是 5023 和 5102,所以当 5023 不可用时,我希望它重定向到 5102。

请帮忙,提前致谢。

配置.json

{
  "Routes": [
    {
       "DownstreamPathTemplate": "/GetProductDetails",
       "DownstreamScheme": "http",
       "DownstreamHostAndPorts": [
         {
           "Host": "localhost",
           "Port": 5023
         },
         {
           "Host": "localhost",
           "Port": 5102
         }
       ],

       "UpstreamPathTemplate": "/",
       "LoadBalancerOptions": {
         "Type": "RoundRobin" 
       },
      "UpstreamHttpMethod": [ "GET" ]
    }
  ]
}

程序.cs

using Ocelot.DependencyInjection;
using Ocelot.Middleware;

var builder = WebApplication.CreateBuilder(args);

builder.Configuration.AddJsonFile(
"configuration.json",optional:false,reloadOnChange:true);

builder.Services.AddOcelot(builder.Configuration);

var app = builder.Build();


app.MapControllers();

var ocelotConf = new OcelotPipelineConfiguration()
{
    PreErrorResponderMiddleware = async (context, next) =>
    {
        if (context.Response != null)
        {

        }
        await next.Invoke();
    }
};

await app.UseOcelot(ocelotConf);

app.Run();

我们可以编写自定义负载均衡器吗?

asp.net-core .net-core api-gateway service-discovery ocelot
1个回答
0
投票

最后经过深思熟虑,我明白了,如果当前主机不活动,我们可以从请求管道处理到下一个调用。

代码如下。

var ocelotConf = new OcelotPipelineConfiguration()
{
    PreErrorResponderMiddleware = async (context, next) =>
    {
        // Initial invoke
        await next.Invoke();
        if (context.Response != null)
        {
            // Checking if the initial invoke is throwing 502
            //(Means service is down)
            if(context.Response.StatusCode == 502)
            {
                // If service is down forwarding to next host
                await next.Invoke();
            }
        }
    }
};

await app.UseOcelot(ocelotConf);
© www.soinside.com 2019 - 2024. All rights reserved.