一.背景
二:consul的基本概念
組成 consul 集羣的每個成員上都要運行一個 agent,可以通過 consul agent 命令來啓動。agent 可以運行在 server 狀態或者 client 狀態。自然的,運行在 server 狀態的節點被稱爲 server 節點;運行在 client 狀態的節點被稱爲 client 節點。
client 節點
負責轉發所有的 RPC 到 server 節點。本身無狀態,且輕量級,因此,可以部署大量的 client 節點。
server 節點
負責組成 cluster 的複雜工作(選舉、狀態維護、轉發請求到 lead),以及 consul 提供的服務(響應 RCP 請求)。考慮到容錯和收斂,一般部署 3 ~ 5 個比較合適。
三.安裝和啓動
下載後解壓,直接運行
consul需要用agent啓動,啓動模式可以是server和client
以window單機啓動server爲例:
配置config.conf文件
{
"datacenter":"dc1",//數據中心名稱
"data_dir": "D:\\consul\\consul\\data",//數據存儲目錄
"log_level": "INFO",//日誌級別
"node_name": "node1",//server節點名稱
"server": true,//是否開啓服務模式
"ui":true,//是否開啓web-ui
"bind_addr":"192.168.100.110",//綁定的地址
"bootstrap":true,//引用啓動
"ui_dir": "D:\\consul\\consul\\webui"//web-ui地址
}
進入consul根目錄 啓動命令:consul.exe agent -config-file config.conf啓動成功後,瀏覽器打開http://127.0.0.1:8500/ui/ 可以看到整個consul的所有信息
如果需要配置集羣的話
server node1 配置信息
{
"datacenter":"dc1",
"log_level": "INFO",
"node_name": "node1",
"server": true,
"ui":true,
"bind_addr":"192.168.100.110",
"cluster_addr":"10.10.105.71",
"bootstrap":true,
"join":"10.10.105.72"
"ui_dir": "D:\\consul\\consul\\webui"
}
server node2 配置信息
{
"datacenter":"dc1",
"log_level": "INFO",
"node_name": "node2",
"server": true,
"ui":true,
"bind_addr":"192.168.100.111",
"cluster_addr":"10.10.105.72",
"bootstrap":true
}
啓動兩個節點 啓動命令:consul.exe agent -config-file config.conf
四.服務註冊與發現的兩種方式
1.1首先我們來了解用配置註冊服務
{
"service": {
"name": "redis-server1",
"tags": ["master"],
"address": "127.0.0.1",
"port": 6379,
"checks": [
{
"http": "http://localhost:6379",
"interval": "10s"
}
]
}
}
{
"datacenter":"dc1",
"log_level": "INFO",
"node_name": "node3",
"server": false,
"bind_addr":"192.168.100.112",
"config_dir":"./conf"
}
把json文件放到conf文件夾下面,利用consul.exe agent -config-file config.conf ,client註冊一個redis服務。json文件定義中包含服務的name、address、port等,還包含一個服務檢測的配置,這裏 我們每隔10s對服務進行一次健康檢查。同理,我們可以在其它節點上也建立同樣配置文件(需重啓,並帶上 -config-dir命令行選項),服務註冊就這麼簡單。
1.2使用java代碼註冊服務
<dependency>
<groupId>com.orbitz.consul</groupId>
<artifactId>consul-client</artifactId>
<version>0.12.3</version>
</dependency>
註冊代碼: Consul client = Consul.builder().build();
String serviceName = UUID.randomUUID().toString();
String serviceId = UUID.randomUUID().toString();
client.agentClient().register(8080, new URL("http://localhost:1337/health"), 1000L, serviceName, serviceId);
這樣就完成了服務註冊,並且添加了健康檢查的url,比較簡單。2.2.java代碼發現服務
HealthClient healthClient = Consul.newClient().healthClient();
ConsulResponse<List<ServiceHealth>> response = client2.healthClient().getHealthyServiceInstances(serviceName);//獲取健康的服務
ServiceHealthCache svHealth = ServiceHealthCache.newCache(healthClient, serviceName);//創建今天服務
svHealth.start();//開始監聽服務
這裏分析下consul和zookeeper服務變更通知的區別: