Cousul 可以作為注冊中和配置中心來使用,本來主要介紹 Spring Cloud 整合 Consul 的使用,文中所使用到的軟體版本:Java 1.8.0_191、Consul 1.11.1、Spring Boot 2.3.12.RELEASE、Spring Cloud Hoxton.SR12,
1、Consul 作為注冊中心
1.1、引入依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-consul-discovery</artifactId> </dependency>
1.2、配置(application.yml)
spring: cloud: consul: host: 10.40.96.20 port: 8500 discovery: register: true prefer-ip-address: true health-check-critical-timeout: 10s #監控檢查失敗多長時間后,洗掉注冊的服務
如果需要呼叫的服務在另外一個資料中心,則需要增加 spring.cloud.consul.datacenters 配置;如在本服務在資料中心 dc2,需呼叫的一個服務(scdemo-server)在另一個資料中心 dc1,則配置如下:
spring: cloud: consul: host: 10.40.96.131 port: 8500 discovery: register: true prefer-ip-address: true datacenters: scdemo-server: dc1 health-check-critical-timeout: 10s #監控檢查失敗多長時間后,洗掉注冊的服務
注:在使用新版本(SpringBoot 2.4.12/2.4.13/2.5.6/2.5.7/2.5.8、SpringCloud 2020.0.4)時,spring.cloud.consul.datacenters 配置沒有效果,還是報找不到服務,應該是新版本還有 bug,
配置完成后,正常啟動服務即可,
1.3、洗掉無效的服務
如果在注冊服務是未設定 spring.cloud.consul.discovery.health-check-critical-timeout 引數,可以通過命令列或 API 來洗掉無效的服務,
命令列:
./consul services deregister -id=scdemo-client-9002
API:
curl -X PUT http://10.40.96.10:8500/v1/agent/service/deregister/scdemo-client-9002
2、Consul 作為配置中心
2.1、引入依賴
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-consul-config</artifactId> </dependency>
2.2、配置(bootstrap.yml)
spring: cloud: consul: host: 10.40.96.10 port: 8500 config: format: yaml prefix: config #配置所在目錄 data-key: data #配置的 key
2.3、在 Consul 控制臺配置 Key
key 為:config/scdemo-server/data (scdemo-server 為對應的服務名)
value 為:
test:
k1: v1
k2: v22
如下圖:
2.4、獲取配置資訊
@Autowired private Environment environment; @Scheduled(cron = "0/10 * * * * *") public void test() { logger.info("test.k1={}", environment.getProperty("test.k1")); logger.info("test.k2={}", environment.getProperty("test.k2")); }
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/419903.html
標籤:Java
上一篇:陣列回圈不顯示所有資料?
下一篇:返回列表