【问题标题】:Dynamic service name with ocelot and consul带有 ocelot 和 consul 的动态服务名称
【发布时间】:2019-05-27 08:51:38
【问题描述】:

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

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

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

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

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

谢谢

【问题讨论】:

    标签: consul service-discovery api-gateway ocelot


    【解决方案1】:

    我一直在为自己寻找相同的解决方案,但在 GitHub 上只找到了一个 comment,它对我帮助很大

    因此,您需要创建自定义中间件来重写 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();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-04
      • 1970-01-01
      • 2020-09-19
      • 2017-09-30
      • 2022-05-01
      • 1970-01-01
      • 2011-03-18
      相关资源
      最近更新 更多