3

我正在使用带有 Consul 和服务发现的 Ocelot 和 API 网关。我正在使用动态名称在 Consul 中注册服务,例如:service.name.1234 和 service.name.5678

此服务是静态的,根本不打算扩展

由于我正在使用 Ocelot,我希望能够将请求路由到所需的服务,但由于名称是动态的,我需要使用查询字符串参数作为服务名称

示例:http ://myapp.com/service/1234 应该重定向到名为 service.name.1234 的容器

有什么方法可以同时使用这两种产品吗?或者其他产品?

谢谢

4

1 回答 1

0

我一直在为自己寻找相同的解决方案,但在 GitHub 上只发现了一条评论,它对我帮助很大

因此,您需要创建自定义中间件来重写 Ocelot 的 DownstreamRoute:

public static async Task InvokeAsync(HttpContext httpContext, Func<Task> next)
    {
        
        var downstreamRoute = httpContext.Items.DownstreamRoute();

        var yourServiceName = //get query string parameter from httpContext;

        //rewrite any parameter that you want
        httpContext.Items.UpsertDownstreamRoute(
            new DownstreamRoute(
                downstreamRoute.Key,
                downstreamRoute.UpstreamPathTemplate,
                downstreamRoute.UpstreamHeadersFindAndReplace,
                downstreamRoute.DownstreamHeadersFindAndReplace,
                downstreamRoute.DownstreamAddresses,
                tenantServiceName,
                ...
            ));
    }

然后在 Startup.cs 中调用它:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // some other code

    var configuration = new OcelotPipelineConfiguration
            {
                PreQueryStringBuilderMiddleware = async (ctx, next) =>
                {
                    await RouteContextRetrieverMiddleware.InvokeAsync(ctx, next);

                    await next.Invoke();
                }
            };

            app.UseOcelot(configuration).GetAwaiter().GetResult();
}
于 2021-06-17T16:12:42.293 回答