gpt4 book ai didi

consul - ocelot 和 consul 的动态服务名称

转载 作者:行者123 更新时间:2023-12-05 07:27:24 26 4
gpt4 key购买 nike

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

此服务是有状态的,根本不需要扩展

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

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

有什么方法可以同时使用这两种产品来实现这一目标?或者其他产品?

谢谢

最佳答案

我一直在寻找相同的解决方案,但只找到一个 comment在 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();
}

关于consul - ocelot 和 consul 的动态服务名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53976998/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com