可以对下游的服务进行负载均衡。
提供了下面几种负载均衡:
- LeastConnection - tracks which services are dealing with requests and sends new requests to service with least existing requests. The algorythm state is not distributed across a cluster of Ocelot’s.
- RoundRobin - loops through available services and sends requests. The algorythm state is not distributed across a cluster of Ocelot’s.
- NoLoadBalancer - takes the first available service from config or service discovery.
- CookieStickySessions - uses a cookie to stick all requests to a specific server. More info below.
必须要在配置你面指定你要使用的复杂均衡类型。
Configuration
下面的例子中一个ReRoute设置了多个下游服务,并且使用了LeastConnection
负载均衡。这个是设置负载均衡最简单的方式。
{
"DownstreamPathTemplate": "/api/posts/{postId}",
"DownstreamScheme": "https",
"DownstreamHostAndPorts": [
{
"Host": "10.0.1.10",
"Port": 5000,
},
{
"Host": "10.0.1.11",
"Port": 5000,
}
],
"UpstreamPathTemplate": "/posts/{postId}",
"LoadBalancerOptions": {
"Type": "LeastConnection"
},
"UpstreamHttpMethod": [ "Put", "Delete" ]
}
Service Discovery
下面的例子通过service discovery provider设置ReRoute,并且使用了LeastConnection
负载均衡:
{
"DownstreamPathTemplate": "/api/posts/{postId}",
"DownstreamScheme": "https",
"UpstreamPathTemplate": "/posts/{postId}",
"UpstreamHttpMethod": [ "Put" ],
"ServiceName": "product",
"LoadBalancerOptions": {
"Type": "LeastConnection"
},
"UseServiceDiscovery": true
}
CookieStickySessions
这个是为了解决有了负载均衡,但是没有独立session state服务器造成的问题而出现的。
配置如下:
{
"DownstreamPathTemplate": "/api/posts/{postId}",
"DownstreamScheme": "https",
"DownstreamHostAndPorts": [
{
"Host": "10.0.1.10",
"Port": 5000,
},
{
"Host": "10.0.1.11",
"Port": 5000,
}
],
"UpstreamPathTemplate": "/posts/{postId}",
"LoadBalancerOptions": {
"Type": "CookieStickySessions",
"Key": "ASP.NET_SessionId",
"Expiry": 1800000
},
"UpstreamHttpMethod": [ "Put", "Delete" ]
}
Type要设置为CookieStickySessions
, Key
是session对应的cookie名,Expiry
设置过期,单位为毫秒 。
If you have multiple ReRoutes with the same LoadBalancerOptions then all of those ReRoutes will use the same load balancer for there subsequent requests. This means the sessions will be stuck across ReRoutes.
Please note that if you give more than one DownstreamHostAndPort or you are using a Service Discovery provider such as Consul and this returns more than one service then CookieStickySessions uses round robin to select the next server. This is hard coded at the moment but could be changed.