原文html
你能夠指定一個service discovery provider,ocelot將使用它來找下游的host和port。web
下面的配置要放在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
算法。api
{ "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獲取服務配置的頻率。ide
服務須要以下同樣添加到Consul中去。注意了這裏不須要添加scheme。post
"Service": { "ID": "some-id", "Service": "some-service-name", "Address": "localhost", "Port": 8080 }
可使用ACL和Consul交互,ocelot支持添加X-Consul-Token
請求頭。爲了啓用,必須添加下面的配置:url
"ServiceDiscoveryProvider": { "Host": "localhost", "Port": 8500, "Token": "footoken" }
Ocelot在每次請求consul的時候會帶上這個token。spa
這種模式下,ocelot會使用上游path的第一個segment去service discovery provider中查找對應的下游服務。code
例如,若是經過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", } }