如何解决ASP.NET Core 3.1中的Ocelot API Gateway自定义聚合器问题
我正在使用ASP.NET中的Ocelot实现自定义聚合器,它在Startup.cs Ocelot中间件中引发了错误。但是,两个微服务都可以正常工作,并且可以独立获取数据。
Startup.cs
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application,visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddOcelot()
.AddSingletonDefinedAggregator<MyAggregator>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public async void Configure(IApplicationBuilder app,IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
await app.USEOcelot();
}
}
这是我的用于不同微服务路由的ocelot.json文件。
ocelot.json
{
"ReRoutes": [
{
"DownstreamPathTemplate": "/user/getUser","DownstreamScheme": "https","DownstreamHostAndPorts": [
{
"Host": "localhost","Port": "44378"
}
],"UpstreamPathTemplate": "/getUser","Key": "User"
},{
"DownstreamPathTemplate": "/product/getProduct","Port": "44357"
}
],"UpstreamPathTemplate": "/getProduct","Key": "Product"
}
],"Aggregates": [
{
"ReRouteKeys": [
"User","Product"
],"UpstreamPathTemplate": "/UserAndProduct"
}
],"GlobalConfiguration": {
"BaseUrl": "http://localhost:5000/"
}
}
我的自定义聚合器类
MyAggregator.cs
public class MyAggregator : IDefinedAggregator
{
public async Task<DownstreamResponse> Aggregate(List<HttpContext> responses)
{
var one = await responses[0].Items.DownstreamResponse().Content.ReadAsstringAsync();
var two = await responses[1].Items.DownstreamResponse().Content.ReadAsstringAsync();
var contentBuilder = new StringBuilder();
contentBuilder.Append(one);
contentBuilder.Append(two);
var stringContent = new StringContent(contentBuilder.ToString())
{
Headers = { ContentType = new MediaTypeHeaderValue("application/json") }
};
return new DownstreamResponse(stringContent,HttpStatusCode.OK,new List<keyvaluePair<string,IEnumerable<string>>>(),"OK");
}
}
解决方法
您忘记在ocelot.json
文件中提及您的自定义聚合器。每当您点击/UserAndProduct
时,Ocelot都需要了解您的自定义聚合器。
“集合”:[ { “ ReRouteKeys”:[ “用户”, “产品” ], “ UpstreamPathTemplate”:“ / UserAndProduct” } ]
ocelot的最新版本发生了重大变化。使用钥匙
Routes
,而不是ReRoutes
。您可以使用以下json文件。
{
"Routes": [
{
"DownstreamPathTemplate": "/user/getUser","DownstreamScheme": "https","DownstreamHostAndPorts": [
{
"Host": "localhost","Port": "44378"
}
],"UpstreamPathTemplate": "/getUser","Key": "User"
},{
"DownstreamPathTemplate": "/product/getProduct","Port": "44357"
}
],"UpstreamPathTemplate": "/getProduct","Key": "Product"
}
],"Aggregates": [
{
"RouteKeys": [
"User","Product"
],"UpstreamPathTemplate": "/UserAndProduct","Aggregator": "MyAggregator"
}
],"GlobalConfiguration": {
"BaseUrl": "http://localhost:5000/"
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。