你可以指定一個service discovery provider,ocelot將使用它來找下游的host和port。
Consul
下面的配置要放在GlobalConfiguration
中。如果你沒有指定host和port,那么就需要一個service discovery provider,默認使用的是Consul。
"ServiceDiscoveryProvider": {
"Host": "localhost",
"Port": 8500,
"Type": "Consul"
}
為了讓Ocelot知道一個ReRoute是通過service discovery provider找host和port,必須給ReRoute加上ServiceName
,UseServiceDiscovery
。如果要使用負載均衡處理downstream的請求,還要指定負載均衡的算法。目前Ocelot支持RoundRobin
和LeastConnection
算法。
{
"DownstreamPathTemplate": "/api/posts/{postId}",
"DownstreamScheme": "https",
"UpstreamPathTemplate": "/posts/{postId}",
"UpstreamHttpMethod": [ "Put" ],
"ServiceName": "product",
"LoadBalancerOptions": {
"Type": "LeastConnection"
},
"UseServiceDiscovery": true
}
如果你想直接從consul中拉取最新的services,而不是每次請求都去consul中請求的話,可以加上如下配置:
"ServiceDiscoveryProvider": {
"Host": "localhost",
"Port": 8500,
"Type": "PollConsul",
"PollingInterval": 100
}
PollingInterval
的單位為毫秒,它告訴Ocelot去調用Consul獲取服務配置的頻率。
服務需要如下一樣添加到Consul中去。注意了這里不需要添加scheme。
"Service": {
"ID": "some-id",
"Service": "some-service-name",
"Address": "localhost",
"Port": 8080
}
ACL Token
可以使用ACL和Consul交互,ocelot支持添加X-Consul-Token
請求頭。為了啟用,必須添加下面的配置:
"ServiceDiscoveryProvider": {
"Host": "localhost",
"Port": 8500,
"Token": "footoken"
}
Ocelot在每次請求consul的時候會帶上這個token。
Dynamic Routing
這種模式下,ocelot會使用上游path的第一個segment去service discovery provider中查找對應的下游服務。
例如,如果通過https://api.mywebsite.com/product/products
這個url請求ocelot。ocelot會使用這個url種的第一個segment,也就是product
,作為key去consul里面查找服務。如果consul返回了一個service,ocelot會請求這個service的host+port+原始url第一個segment后面的path來訪問下游,這個例子中會訪問http://hostfromconsul:portfromconsul/products
。
為了啟用dynamic routing,配置里面的ReRoutes應該是空的。另外需要指定service discovery provider。
{
"ReRoutes": [],
"Aggregates": [],
"GlobalConfiguration": {
"RequestIdKey": null,
"ServiceDiscoveryProvider": {
"Host": "localhost",
"Port": 8500,
"Type": "Consul",
"Token": null,
"ConfigurationKey": null
},
"RateLimitOptions": {
"ClientIdHeader": "ClientId",
"QuotaExceededMessage": null,
"RateLimitCounterPrefix": "ocelot",
"DisableRateLimitHeaders": false,
"HttpStatusCode": 429
},
"QoSOptions": {
"ExceptionsAllowedBeforeBreaking": 0,
"DurationOfBreak": 0,
"TimeoutValue": 0
},
"BaseUrl": null,
"LoadBalancerOptions": {
"Type": "LeastConnection",
"Key": null,
"Expiry": 0
},
"DownstreamScheme": "http",
"HttpHandlerOptions": {
"AllowAutoRedirect": false,
"UseCookieContainer": false,
"UseTracing": false
}
}
}
通過Ocelot還可以設置DynamicReRoutes
,通過設置它來設置下游服務的rate limiting。
{
"DynamicReRoutes": [
{
"ServiceName": "product",
"RateLimitRule": {
"ClientWhitelist": [],
"EnableRateLimiting": true,
"Period": "1s",
"PeriodTimespan": 1000.0,
"Limit": 3
}
}
],
"GlobalConfiguration": {
"RequestIdKey": null,
"ServiceDiscoveryProvider": {
"Host": "localhost",
"Port": 8523,
},
"RateLimitOptions": {
"ClientIdHeader": "ClientId",
"QuotaExceededMessage": "",
"RateLimitCounterPrefix": "",
"DisableRateLimitHeaders": false,
"HttpStatusCode": 428
}
"DownstreamScheme": "http",
}
}