1. 程式人生 > >【Consul】Consul實踐指導-服務註冊(Service)

【Consul】Consul實踐指導-服務註冊(Service)

        服務發現是consul的另一主要功能。Consul Agent提供簡單的Service定義格式用於申報服務的可用性,並與健康檢查相關聯。如果健康檢查與服務關聯,則認為服務是應用級的。服務可以定義在配置檔案中或在執行時通過HTTP介面新增。 

1.1.1  Service Definition

        指令碼服務定義示例如下:

{
  "service": {
    "name": "redis",
    "tags": ["master"],
    "address": "127.0.0.1",
    "port": 8000,
    "enableTagOverride": false,
    "checks": [
      {
        "script": "/usr/local/bin/check_redis.py",
        "interval": "10s"
      }
    ]
  }
}

        定義服務必須包含name欄位,其他欄位id、tags、address、port、check、enableTagOverride是可選欄位。如果id欄位沒有定義,那麼會被賦值為name。在當前節點上,服務ID必須是唯一的,name是可以重複的,那麼id必須配置。

        Tags欄位是增強配置的可讀性,consul不使用,可以說明當前節點是master還是slave,及其版本等資訊。

        Address欄位可以指定一個給定服務的IP。預設情況下,通常使用agent的IP,不是必須的。使用埠port可以使得面向服務的體系架構更容易配置。

        服務與健康檢查關聯,可以替換失敗節點和資料庫。健康檢查很好地集成了DNS介面,如果服務健康檢查失敗或者節點存在系統級檢查失敗。DNS介面將從服務佇列中刪除該節點。

        Check必須是Script、HTTP、TCP、TTL四種類型中的一種。Script型別需要提供Script指令碼和interval變數。HTTP型別必須提供http和Interval欄位。TCP型別需要提供tcp和Interval欄位,TTL型別秩序提供ttl。Check的name欄位是自動通過service:<service-id>生成,如果有多個service,則由service:<service-id>:<num>生成

(詳情參見check配置-http://blog.csdn.net/younger_china/article/details/52243759) 

        Service配置是可以過載的,兩種方法,1. 傳送SIGHUP 訊號到Agent;2. 通過HTTP API動態配置。

1.1.2  Multiple Service Definitions

        使用services欄位,示例如下:

{
  "services": [
    {
      "id": "red0",
      "name": "redis",
      "tags": [
        "master"
      ],
      "address": "127.0.0.1",
      "port": 6000,
      "checks": [
        {
          "script": "/bin/check_redis-p 6000",
          "interval": "5s",
          "ttl": "20s"
        }
      ]
    },
    {
      "id": "red1",
      "name": "redis",
      "tags": [
        "delayed",
        "slave"
      ],
      "address": "127.0.0.1",
      "port": 7000,
      "checks": [
        {
          "script": "/bin/check_redis-p 7000",
          "interval": "30s",
          "ttl": "60s"
        }
      ]
    },
    ...
  ]
}


1.1.3 Service and Tag Names with DNS

        Consul exposes service definitions and tags over the DNS interface. DNS queries have a strict set of allowed characters anda well-defined format that Consul cannot override. While it is possible toregister services or tags with names that don't match the conventions, thoseservices and tags will not be discoverable via the DNS interface. It isrecommended to always use DNS-compliant service and tag names.

DNS-compliant service and tag names may contain any alpha-numericcharacters, as well as dashes. Dots are not supported because Consul internallyuses them to delimit service tags.