1.什么是Consul?
Consul是HashiCorp公司推出的開源工具, 用於實現分布式系統的服務發現與配置.與其他分布式服務注冊與發現的方案相比, Consul的方案更“一站式”, 內置了服務注冊與發現框架、分布一致性協議實現、健康檢查、Key/Valu c存儲、多數據中心方案, 不再需要依賴其他工具(比如ZooKeeper等) .使用起來也較為簡單.Consul使用Go語言編寫, 因此具有天然可移植性(支持Linux、Windows和MacOSX) :安裝包僅包含一個可執行文件,方便部署, 與Docker等輕量級容器可無縫配合。
2.Consul安裝
https://www.consul.io/downloads.html
下載完成后解壓,打開CMD終端,進入consul.exe所在目錄,執行如下命令啟動Consul服務。
#進入consul.exe所在目錄 cd 你的目錄 #啟動服務,-dev表示開發模式運行,另外還有-server表示服務模式運行 consul agent –dev
啟動成功后訪問localhost:8500,查看是否啟動成功
3.monitor改造
改造mango-monitor工程,作為服務注冊到注冊中心。
3.1 添加依賴
在pom.xml中添加Spring Cloud和Consul注冊中心依賴。
注意:Spring Boot2.1后的版本會出現Consul服務注冊上的問題,可能是因為配置變更或者支持方式發生改變,由於版本太新,網上也沒有相關解決方案,所以這里吧spring Boot版本調整為2.0.4,Spring Cloud版本使用最新的穩定發布版Finchley.RELEASE。
<!--consul--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-consul-discovery</artifactId> </dependency> <!--srping cloud--> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Finchley.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>
3.2 配置文件
server.port=8000 spring.application.name=mango-monitor spring.cloud.consul.host=localhost spring.cloud.consul.port=8500 #注冊到consul的服務名稱 spring.cloud.consul.discovery.service-name=${spring.application.name}
3.3 修改啟動類
添加@EnableDiscoveryClient
3.4 測試效果
啟動服務監控服務器,訪問localhost:8500,發現服務已經成功注冊到注冊中心。
1