Spring Cloud Consul
項目是針對Consul的服務治理實現。Consul是一個分布式高可用的系統,具有分布式、高可用、高擴展性
Consul
Consul 是 HashiCorp 公司推出的開源工具,用於實現分布式系統的服務發現與配置。與其他分布式服務注冊與發現的方案,Consul的方案更“一站式” ,內置了服務注冊與發現框 架、具有以下性質:
● 分布一致性協議實現
● 健康檢查
● Key/Value存儲
● 多數據中心方案
不再需要依賴其他工具(比如ZooKeeper等)
添加依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-all</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
consul-all依賴提供了哪些功能?
<!--消息總線,提供配置實時刷新,不再依賴中間件-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-bus</artifactId>
</dependency>
<!--consul的配置中心功能-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-config</artifactId>
</dependency>
<!--服務注冊和發現功能-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
bootstarp.yml
這里要注意是要配置在 bootstarp.yml
spring:
application:
name: pig-consul
cloud:
consul:
host: localhost
port: 8500
config:
enabled: true
format: KEY_VALUE
watch:
enabled: true
prefix: pig-config
安裝consul
下載: https://www.consul.io/downloads.html
使用:(dev模式,生成建議cluster模式)
-dev表示開發模式運行,使用-client 參數可指定允許客戶端使用什么ip去訪問,例如-client 127.0.0.1 表示可以使用。
consul agent -dev -client 127.0.0.1
生產配置參考:
https://www.consul.io/intro/getting-started/join.html
http://127.0.0.1:8500/ui/ 去訪問

image
配置config

image
demo
@RestController public class DemoController { @Value("${author}") private String author;
<span class="token annotation builtin">@GetMapping</span><span class="token punctuation">(</span><span class="token string">"/demo"</span><span class="token punctuation">)</span> <span class="token keyword">public</span> String <span class="token function">demo</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span> <span class="token keyword">return</span> author<span class="token punctuation">;</span> <span class="token punctuation">}</span>
}
關於實時刷新配置
spring:
cloud:
consul:
config:
watch:
enabled: true
然后應用要開啟定時任務
@EnableScheduling
總結
- 相較於spring cloud config 的配置中心,使用起來較為麻煩,但是對於實時刷新,這塊要優於spring cloud config 的,不依賴於中間件的消息通知,也不會出現服務下線的問題。
- 這篇文章主要是入門,更高級的使用Consul Config 結合 Git 來做版本控制,請參考我后邊的文章
- 關於pig:基於Spring Cloud、oAuth2.0開發基於Vue前后分離的開發平台,支持賬號、短信、SSO等多種登錄,提供配套視頻開發教程