[译]Ocelot - Request Aggregation
Aggregate ReRoutes用来组合多个ReRoutes,将它们的响应结果映射到一个响应中返回给客户端。
为了使用Aggregate ReRoutes,你必须像下面的ocelot.json
中做些配置。 在下面的例子中,有两个ReRoutes,且它们都有一个Key属性,我们将使用ReRoute里面的key在Aggregate中组合ReRoute。Aggregate 和 ReRoutes的UpstreamPathTemplate
不能重复。Aggregate可以使用ReRoute中出了RequestIdKey
之外的所有配置。
Advanced register your own Aggregators
在ocelot.json
添加Aggregator
属性:
{
"ReRoutes": [
{
"DownstreamPathTemplate": "/",
"UpstreamPathTemplate": "/laura",
"UpstreamHttpMethod": [
"Get"
],
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 51881
}
],
"Key": "Laura"
},
{
"DownstreamPathTemplate": "/",
"UpstreamPathTemplate": "/tom",
"UpstreamHttpMethod": [
"Get"
],
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 51882
}
],
"Key": "Tom"
}
],
"Aggregates": [
{
"ReRouteKeys": [
"Tom",
"Laura"
],
"UpstreamPathTemplate": "/",
"Aggregator": "FakeDefinedAggregator"
}
]
}
添加了一个名为FakeDefinedAggregator
的Aggregator。
还要将这个FakeDefinedAggregator
添加到OcelotBuilder
中:
services
.AddOcelot()
.AddSingletonDefinedAggregator<FakeDefinedAggregator>();
因为FakeDefinedAggregator
注册到了DI容器中,因此可以向下面一样添加依赖到它里面去:
services.AddSingleton<FooDependency>();
services
.AddOcelot()
.AddSingletonDefinedAggregator<FooAggregator>();
上面的例子中,FooAggregator
可以依赖于FooDependency
, 它通过DI容器resolved。
另外,还可以将Aggregator注册为transient生命周期:
services
.AddOcelot()
.AddTransientDefinedAggregator<FakeDefinedAggregator>();
自定义的Aggregator必须实现IDefinedAggregator
接口:
public interface IDefinedAggregator
{
Task<DownstreamResponse> Aggregate(List<DownstreamResponse> responses);
}
通过这个特性,我们可以做许多事情,因为DownstreamResponse
包含了Content, Headers 和 Status Code。如果这个Aggregator其中的一个ReRoute请求时发生了异常,那么将得不到这个ReRoute的DownstreamResponse
。如果抛出了异常,那么会有日志记录。
Basic expecting JSON from Downstream Services
{
"ReRoutes": [
{
"DownstreamPathTemplate": "/",
"UpstreamPathTemplate": "/laura",
"UpstreamHttpMethod": [
"Get"
],
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 51881
}
],
"Key": "Laura"
},
{
"DownstreamPathTemplate": "/",
"UpstreamPathTemplate": "/tom",
"UpstreamHttpMethod": [
"Get"
],
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 51882
}
],
"Key": "Tom"
}
],
"Aggregates": [
{
"ReRouteKeys": [
"Tom",
"Laura"
],
"UpstreamPathTemplate": "/"
}
]
}
如果 ReRoute /tom
返回 {“Age”: 19}
, /laura
返回 {“Age”: 25}
, 那么Aggregator返回:
{"Tom":{"Age": 19},"Laura":{"Age": 25}}
ReRoute key 作为了Aggregator返回字典的key, 响应做为了返回字典的值。
所有downstream services的响应头都会被丢弃掉。
Ocelot返回的content type是 application/json
。
如果downstream services 返回了一个 404,那么aggregator不会为这个downstream service返回任何东西。aggregator不会受此影响返回404, 即使这个aggregator的所有ReRoute都返回了404,它也不会返回404。
Aggregator 只支持 GET
请求方式。