Ocelot + Consul實踐

關於Consul(https://www.consul.io)是一個分佈式,高可用,支持多數據中心的服務發現和配置共享的服務軟件,由 HashiCorp 公司用 Go 語言開發, 基於 Mozilla Public License 2.0 的協議進行開源。 在Consul的文檔上,Consul 支持Service Discovery, Health Checking, Key/Value Store, Multi DataCenter。運用Consul,能夠在系統中build複雜的應用和服務的發現等。本文不是Consul的學習重點,關於更多Consul的學習,可參考:http://blog.csdn.net/column/details/consul.htmlhtml

 

閱讀本博客的前提是對Consul中數據中心,節點,服務,健康檢查等名詞,一些基本的consul命令,Consul UI的使用有必定的瞭解。node

Ocelot對Consul支持是天生集成,在OcelotGateway項目中configuration.json配置就能夠開啓consul+ocelot的使用,這套組合能夠實現什麼功能呢?git

服務註冊,服務發現,API網關(ocelot固有,不做說明),負載均衡,限流,熔錯告警,彈性和瞬態故障處理 github

 

1、服務治理:服務註冊,服務發現web

服務註冊和服務發現都是Consul自有的功能,能夠經過Consul的http api完成註冊或發現,我寫了個NuGet庫ConsulSharp(https://github.com/axzxs2001/ConsulSharp),能夠在.net core下完成服務的註冊和發現,建議服務註冊作到一個統一的管理平臺裏,爲了測試方便,能夠在Consul的配置文裏先配置服務,每次Consul啓動時,自動註冊;關於服務發現,Ocelot自動能夠完成,只須要在OcelotGateway項目中configuration.json進行配置就能夠,接下來咱們看看怎麼配置。json

首先下載Consul: https://www.consul.io/downloads.html,本項目是windows下進行測試bootstrap

再下載Consul配置文件(這個配置文件是適合本例Demo的,可根據具體給你個況調整)https://github.com/axzxs2001/Asp.NetCoreExperiment/tree/master/Asp.NetCoreExperiment/ConsulOcelot/consulwindows

conf文件夾:consul存放配置文件api

dist文件夾:consul UI,一個小的consul信息展現門戶瀏覽器

data文件夾:consul啓動後存放consul的生成的數據和文件,在運行consul前能夠清空此文件夾

Consul的配置文件以下:

{

  "encrypt": "7TnJPB4lKtjEcCWWjN6jSA==",

  "services": [

    {

      "id": "API001",

      "name": "API001",

      "tags": [ "API001" ],

      "address": "192.168.1.99",

      "port": 5001,

      "checks": [

        {

          "id": "API001_Check",

          "name": "API001_Check",

          "http": "http://192.168.1.99:5001/health",

          "interval": "10s",

          "tls_skip_verify": false,

          "method": "GET",

          "timeout": "1s"

        }

      ]

    },

    {

      "id": "API002",

      "name": "API002",

      "tags": [ "API002" ],

      "address": "192.168.1.99",

      "port": 5002,

      "checks": [

        {

          "id": "API002_Check",

          "name": "API002_Check",

          "http": "http://192.168.1.99:5002/health",

          "interval": "10s",

          "tls_skip_verify": false,

          "method": "GET",

          "timeout": "1s"

        }

      ]

    }

  ]

}

 

兩個服務API001和API002,跟着兩個健康檢查API001_Check和API002_Check

 

基於consul服務的配置,如今建立三個asp.net core web api項目

OcelotGateway,網關項目,端口5000;API001業務API項目,端口5001;業務API項目,API002端口5002,代碼參見https://github.com/axzxs2001/Asp.NetCoreExperiment/tree/master/Asp.NetCoreExperiment/ConsulOcelot

OcelotGateway實現引入Ocelot網關,API001,API002實現健康檢查的兩個get請求。

測試服務註冊和發現:

一、 啓動consul

consul agent -server -datacenter=dc1 -bootstrap -data-dir ./data -config-file ./conf -ui-dir ./dist -node=n1 -bind 本機IP -client=0.0.0.0

 

再啓動一個consul,查看狀態,命令:consul operator raft list-peers

結果:

Node  ID                                    Address            State   Voter  RaftProtocol

n1    dad74de2-173d-1c1e-add0-975a243b59eb  192.168.1.99:8300  leader  true   3

用Consul UI查看

services:

 

nodes:

 

能夠看到API001和API002服務,而且健康檢查都是正常的。

 

二、 配置Ocelot網關

configuration.json文件以下(關於ocelot配置文件,詳見http://ocelot.readthedocs.io/en/latest/features/configuration.html):

{

  "ReRoutes": [

    {

      "DownstreamPathTemplate": "/api/values",

      "DownstreamScheme": "http",

      "DownstreamHostAndPorts": [

        {

          "Host": "localhost",

          "Port": 5001

        }

      ],

      "UpstreamPathTemplate": "/api001/values",

      "UpstreamHttpMethod": [ "Get" ],

      "ServiceName": "API001",

      "LoadBalancer": "RoundRobin",

      "UseServiceDiscovery": true,

      "ReRouteIsCaseSensitive": false,

      "QoSOptions": {

        "ExceptionsAllowedBeforeBreaking": 3,

        "DurationOfBreak": 10,

        "TimeoutValue": 5000

      },

      "HttpHandlerOptions": {

        "AllowAutoRedirect": false,

        "UseCookieContainer": false,

        "UseTracing": false

      },

      "AuthenticationOptions": {

        "AuthenticationProviderKey": "",

        "AllowedScopes": []

      },

      "RateLimitOptions": {

        "ClientWhitelist": [ "admin" ],

        "EnableRateLimiting": true,

        "Period": "1m",

        "PeriodTimespan": 15,

        "Limit": 5

      }

    },

    {

      "DownstreamPathTemplate": "/notice",

      "DownstreamScheme": "http",

      "DownstreamHostAndPorts": [

        {

          "Host": "localhost",

          "Port": 5001

        }

      ],

      "UpstreamPathTemplate": "/notice",

      "UpstreamHttpMethod": [ "Post" ],     

      "ReRouteIsCaseSensitive": false,

      "QoSOptions": {

        "ExceptionsAllowedBeforeBreaking": 3,

        "DurationOfBreak": 10,

        "TimeoutValue": 5000

      },

      "HttpHandlerOptions": {

        "AllowAutoRedirect": false,

        "UseCookieContainer": false,

        "UseTracing": false

      },

      "AuthenticationOptions": {

        "AuthenticationProviderKey": "",

        "AllowedScopes": []

      }   

    },

    {

      "DownstreamPathTemplate": "/api/values",

      "DownstreamScheme": "http",

      "DownstreamHostAndPorts": [

        {

          "Host": "localhost",

          "Port": 5002

        }

      ],

      "UpstreamPathTemplate": "/API002/values",

      "UpstreamHttpMethod": [ "Get" ],

      "QoSOptions": {

        "ExceptionsAllowedBeforeBreaking": 3,

        "DurationOfBreak": 10,

        "TimeoutValue": 5000

      },

      "ServiceName": "API002",

      "LoadBalancer": "RoundRobin",

      "UseServiceDiscovery": true,

      "HttpHandlerOptions": {

        "AllowAutoRedirect": false,

        "UseCookieContainer": false

      },

      "AuthenticationOptions": {

        "AuthenticationProviderKey": "",

        "AllowedScopes": []

      },

      "RateLimitOptions": {

        "ClientWhitelist": [ "user" ],

        "EnableRateLimiting": true,

        "Period": "1m",

        "PeriodTimespan": 15,

        "Limit": 5

      }

    }

  ],

  "GlobalConfiguration": {

    "ServiceDiscoveryProvider": {

      "Host": "localhost",

      "Port": 8500

    },

    "RateLimitOptions": {

      "ClientIdHeader": "client_id",

      "QuotaExceededMessage": "Too Many Requests!!!",

      "DisableRateLimitHeaders": false

    }

  }

}

 

啓動OcelotGateway,API001,API002項目,經過http://localhost:5000/api001/values,和http://localhost:5000/api002/values訪問;由於Ocelot配置了Consul的服務治理,因此能夠經過配置的服務名稱和GlobalConfiguratin的Consul http api接口查找到對應服務的地址,進行訪問,這些都是Ocelot幫咱們作,這點很容易證實,能夠修改Consul配置文件中服務的address爲錯誤IP,就會發現經過5000端口訪問不成功。

 

2、負載均衡

負載均衡須要啓動多個API001和API002,才能進行測試,因此發佈API001和API002項目,並複製到一個與192.168.1.99在一個局域網的電腦中,同時把Consul和它的配置,UI文件也複製到這臺電腦上,網關項目OcelotGateway不須要,假設另一臺電腦爲192.168.1.126

首先修改Consul的配置文件以下

{

  "encrypt": "7TnJPB4lKtjEcCWWjN6jSA==",

  "services": [

    {

      "id": "API001",

      "name": "API001",

      "tags": [ "API001" ],

      "address": "192.168.1.126",

      "port": 5001,

      "checks": [

        {

          "id": "API001_Check",

          "name": "API001_Check",

          "http": "http://192.168.1.126:5001/health",

          "interval": "10s",

          "tls_skip_verify": false,

          "method": "GET",

          "timeout": "1s"

        }

      ]

    },

    {

      "id": "API002",

      "name": "API002",

      "tags": [ "API002" ],

      "address": "192.168.1.126",

      "port": 5002,

      "checks": [

        {

          "id": "API002_Check",

          "name": "API002_Check",

          "http": "http://192.168.1.126:5002/health",

          "interval": "10s",

          "tls_skip_verify": false,

          "method": "GET",

          "timeout": "1s"

        }

      ]

    }

  ]

}

 

在192.168.1.126下啓動API001,API002項目

啓動consul

consul agent -server -datacenter=dc1 -data-dir ./data -config-file ./conf -ui-dir ./dist -node=n2 -bind 192.168.1.126

一樣,在192.168.1.126下用Consul UI查看各服務是否正常

 

在192.168.1.99下,把192.168.1.126加到集羣中,命令以下

consul join 192.168.1.126

注意,consul集羣中,consul配置文件中的encrypt,必定要相同,不然沒法放加入同一個集羣

用consul operator raft list-peers查看狀態,會發現n1,n2在一個集羣中了

Node  ID                                    Address             State     Voter  RaftProtocol

n1    dad74de2-173d-1c1e-add0-975a243b59eb  192.168.1.99:8300   leader    true   3

n2    efe954ce-9840-5c66-fa80-b9022167d782  192.168.1.126:8300  follower  true   3

 

些時在瀏覽器中屢次訪問view-source:http://localhost:5000/api001/values或view-source:http://localhost:5000/api002/values,會發現返回的內容是交替出現的,由於只有兩個相同的API在集羣中,這樣就實現了負載均衡。

 

 

3、限流

限流是經過configuration.json配置完成的,具體值詳見http://ocelot.readthedocs.io/en/latest/features/ratelimiting.html

每一個要限流Route中

  

    "RateLimitOptions": {

        "ClientWhitelist": [ "admin" ],

        "EnableRateLimiting": true,

        "Period": "1m",

        "PeriodTimespan": 15,

        "Limit": 5

      }

 

GlobalConfiguration中

    "RateLimitOptions": {

      "ClientIdHeader": "client_id",

      "QuotaExceededMessage": "too more request",

      "DisableRateLimitHeaders": false

}

 

須要說明的是若是配置ClientWithelist白名單,須要在訪問api的客戶端添加一個Header項目,key爲client_id,值爲admin,此客戶端就不受限流控制

爲了測試限流建立 TestClient控制檯程序進行測試,交果以下圖,在一分鐘內,用adminclinet訪問API001超過五次也能夠,訪問API002,只能五次

 

 

4、熔錯告警

熔斷保護在Consul中和Ocelot中都有實現,意義當一個服務不正常時,首先不影響正常使用(由於服務做了集羣,能夠把請求轉到別的服務器上),二是發生問題,應該用所告警。Ocelot負載均衡能夠自動發現服務出問題(Consul有健檢查),並中止對異常服務請求;告警是經過Consul配置文件實現的,關於watches參看https://www.consul.io/docs/agent/watches.html

{

  "watches": [

    {

      "type": "checks",

      "handler_type": "http",

      "state": "critical",

      "http_handler_config": {

        "path": "http://192.168.1.99:5000/notice",

        "method": "POST",

        "timeout": "10s",

        "header": { "Authorization": [ "token" ] }

      }

    }

  ]

}

 

在consul啓動時,會加載conf下的全部json文件,由於是json內容是watches節點,consul會做特定處理。

同時http://192.168.1.99:5000/notice映射的http://localhost:5001/notice中做了一個發郵件的操做,把發生異常的服務信息發送給對應郵箱,這裏注意,測試時,不要關了API001測試,由於發郵件的功能在這個項目裏,能夠關掉API002測試,真實環境中,這塊確定是獨立項目處理,而且採用集羣的,效果以下:

 

關掉192.168.1.99下的API2,做業報警郵件會提示準確的檢查錯誤和服務名稱。

 

5、彈性和瞬態故障處理

彈性和瞬態故障處理,是Ocelot內置的功能,在網關轉發每一個請求時,會用Polly(https://github.com/App-vNext/Polly)處理,設置詳見http://ocelot.readthedocs.io/en/latest/features/qualityofservice.html,開發上不做任何處理。

相關文章
相關標籤/搜索