最近一段時間開始了一個新項目,幾個同事共同開發,同時使用了PHP和JAVA兩種語言,分紅了各個模塊,在相互調用時的配置難以維護,因而就開始尋找服務發現的方案,spring 系列的目前提供了eureka、consul、zookeeper,最終選擇consul.node
eureka由JAVA語言開發,在spring cloud中使用方便,容易配置,是首先想到的方案,但基於如下緣由放棄:spring
consul由GO語言開發,是專門用來作服務發現的,具備服務註冊、服務必現、服務檢測、UI管理、命令管理、API管理、數據存儲等;且spring在此基礎上作了封裝,優先採用;bootstrap
zooKeeper最早使用於hadoop集羣管理,用來維護集羣狀態,是一個大而全的組件,學習成本略高app
consul agent -server -bootstrap-expect=1 -data-dir=/data/data/consul/consul1 -node=master_1 -bind=0.0.0.0 -client=0.0.0.0 -enable-script-checks=true -config-dir=/etc/consul/consul1 -ui
//consul-all包含consul-bus、consul-discovery、consul-config三部分 <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-consul-all</artifactId> </dependency>
spring: cloud: consul: host: 192.168.1.40 port: 8500 discovery: heartbeat: enabled: true enabled: true register: true deregister: true prefer-ip-address: true instance-id: ${spring.application.name}:${random.value} # 只查詢有效的記錄 query-passing: true config: # 在consul中配置的key路徑爲: config/cloud-consul/key 在啓動或更新時會覆蓋項目中原先配置 format: key_value enabled: true # 全部項目共用的配置 consul的配置路徑爲: config/application/key default-context: application data-key: data prefix: config
@SpringBootApplication @EnableDiscoveryClient
//經過feign或restTemplate便可遠程調用 @Autowired private ConsulDiscoveryClient discoveryClient; public List<ServiceInstance> test2(String serviceName){ List<ServiceInstance> instanceList = discoveryClient.getInstances(serviceName); return instanceList; }
consul自帶數據存儲功能,是config-client和config-server的替代方案,因爲上文已經引入consul-all
功能,已包含consul-config功能,因此consul的配置位置要由application.yml
轉到bootstrap.yml
中,以官方的說明,consul中的數據將會在一個特定的啓動階段加入到spring容器中,當consul中數據變動時,會觸發refresh操做,完成參數的熱更新;負載均衡
config: # 在consul中配置的key路徑爲: config/cloud-consul/key 在啓動或更新時會覆蓋項目中原先配置 format: key_value enabled: true # 全部項目共用的配置 consul的配置路徑爲: config/application/key default-context: application data-key: data prefix: config
經過consul-ui或命令設置屬性
dom
在須要同步更新的類上加上@RefreshScope
的註解ide
更改consul中的key值,觸發更新
oop
注意內容:
全局的配置屬性所在路徑:/config/application/
或 /config/application,profile
,項目配置屬性全部路徑: /config/service-name
或 /config/service-name,profile
學習
query-passing
的屬性爲false時,須要手動註銷失效節點,方法請參考consul官方文檔;最好的教程就是官方文檔,把consul和spring-cloud-consul文檔過一遍,大部分問題均可以解決,若是有一些弄不清楚,就google吧.............. 若是發現有任何錯誤,歡迎各位大神指正ui