Consul學(xué)習(xí)
Consul是什么
Consul是一個服務(wù)管理軟件宇攻。支持多數(shù)據(jù)中心下,分布式高可用的当凡,服務(wù)發(fā)現(xiàn)和配置共享。采用 Raft 算法,用來保證服務(wù)的高可用纠俭。
安裝Consul服務(wù)端
Consul和Eureka不同沿量,Eureka只需要在項目中加入服務(wù)端依賴,就可以作為服務(wù)端使用冤荆;Consul需要從官網(wǎng)下載朴则,并單獨安裝。
官網(wǎng)下載地址:https://www.consul.io/downloads.html
上傳到服務(wù)器
unzip consul_1.5.3_linux_amd64.zip
./consul -v 查看版本
啟動Consul服務(wù)端
開發(fā)模式啟動單節(jié)點
./consul agent -dev -ui -client 0.0.0.0 啟動命令钓简,添加紅色部分才能被外網(wǎng)訪問乌妒,并有web頁面
curl 192.168.78.131:8500/v1/catalog/nodes查看consul節(jié)點
集群模式啟動
- 創(chuàng)建4臺虛擬機
- 啟動集群汹想,三個service和一個client
2.1 ./consul agent -server -bootstrap-expect 3 -data-dir /tmp/consul -node=c1 -ui -client 0.0.0.0 -bind 192.168.1.109 -join 192.168.1.149
2.2 ./consul agent -server -bootstrap-expect 3 -data-dir /tmp/consul -node=c2 -ui -client 0.0.0.0 -bind 192.168.1.151 -join 192.168.1.149
2.3 ./consul agent -server -bootstrap-expect 3 -data-dir /tmp/consul -node=c3 -ui -client 0.0.0.0 -bind 192.168.1.152 -join 192.168.1.149
2.4 ./consul agent -data-dir /tmp/consul -node=c4 -ui -client 0.0.0.0 -bind 192.168.1.116 -join 192.168.1.149 -
查看集群成員 ./consul members
image.png -
查看成員角色:./consul operator raft list-peers
image.png
tips: 各參數(shù)含義
- agent:Consul的核心命令,主要作用有維護成員信息撤蚊、運行狀態(tài)檢測古掏、聲明服務(wù)以及處理請求等
- -server:就是代表server模式
- -ui:代表開啟web 控制臺
- -bootstrap-expect:代表想要創(chuàng)建的集群數(shù)目,官方建議3或者5
- -data-dir:數(shù)據(jù)存儲目錄
- -node:代表當(dāng)前node的名稱
- -client:應(yīng)該是一個客戶端服務(wù)注冊的地址侦啸,可以和當(dāng)前server的一致也可以是其他主機地址槽唾,系統(tǒng)默認是127.0.0.1
- -bind:集群通訊地址
- -join:加入的集群地址
服務(wù)注冊
通過HTTP API注冊服務(wù)
注冊一個ID為“test001”,name為“test”的服務(wù):curl -X PUT -d '{"id": "test001","name": "test","address": "127.0.0.1","port": 8080,"tags": ["dev"]}' http://192.168.78.131:8500/v1/agent/service/register
查看服務(wù)是否注冊成功
2.1 curl http://192.168.78.131:8500/v1/catalog/service/test 查看服務(wù)信息
2.2 curl http://192.168.78.131:8500/v1/health/service/test?passing 健康檢查
2.3 http://192.168.78.131:8500打開管理頁面查看已注冊的服務(wù)
通過項目注冊服務(wù)
- 添加依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-actuator-autoconfigure</artifactId>
</dependency>
- 配置文件
spring:
application:
name: consul-client
cloud:
consul:
host: 192.168.78.131
port: 8500
discovery:
register: true
service-name: ${spring.application.name}
tags: dev
health-check-path: /actuator/health
ip-address: 192.168.1.107
prefer-ip-address: true
management:
endpoints:
web:
exposure:
include: "*"
啟動項目
-
http://192.168.78.131:8500打開管理頁面查看已注冊的服務(wù)
image.png 防火墻需要關(guān)閉匹中,否則service check訪問不通夏漱。
ip-address: 192.168.1.107 一定要有,為本機地址顶捷,否則找不到本機
prefer-ip-address: true 一定要開啟