1. 程式人生 > >consul作為資料配置中心.md

consul作為資料配置中心.md

consul作為資料配置中心

基於spring boot 2.0.5.RELEASE

依賴

dependencies {
  //	服務註冊和發現功能
	compile('org.springframework.cloud:spring-cloud-starter-consul-discovery')
  //	consul的配置中心功能
	compile('org.springframework.cloud:spring-cloud-starter-consul-config')
  //這個要引入
	compile('org.springframework.boot:spring-boot-starter-web')
	compile('org.springframework.boot:spring-boot-configuration-processor')
	testCompile('org.springframework.boot:spring-boot-starter-test')
}

配置檔案

分別建立三個配置檔案application.yml,application-dev.yml,bootstrap.yml:

application.yml配置檔案:


spring:
  profiles:
    active: dev

application-dev.yml配置檔案:

server:
  port: 8080
spring:
  application:
    name: demo-consul

bootstrap.yml配置檔案:

spring:
  cloud:
    consul:
      port: 8500
      host: localhost
      config:
        enabled: true
        format: YAML
        data-key: data  //kv中k的字尾(suffix)
      discovery:
        health-check-path: /health
        health-check-interval: 10s
        enabled: true
        instance-id: ${spring.application.name}
        tags: dev, dev1
        service-name: ${spring.application.name}

在consul中配置

在consul中配置配置kv,預設是config資料夾, 現在配置的是config/application,dev/data,也可以配置config/demo-consul/data,application是指所有的專案,dev是指dev配置檔案,而demo-consul僅僅是取demo-consul專案下的配置檔案

在這裡插入圖片描述

測試

RedisConfig.java:

@ConfigurationProperties(prefix = "redis.config")
public class RedisConfig {

    private String url;
    private
int port; private int timeOut; //omit... }

ResourceController.java:

@RestController
public class ResourceController {

    @Value("${memo}")
    private String memo;

    @Autowired
    private RedisConfig redisConfig;

    @RequestMapping(value = "/ping", method = RequestMethod.GET)
    private String ping(){
        System.out.println("name: "+ memo);
        return "name: " + memo+ " redis config: "+ redisConfig;
    }
}

DemoConsulApplication.java:

@SpringBootApplication
@EnableDiscoveryClient
@EnableConfigurationProperties({RedisConfig.class})
public class DemoConsulApplication {


	public static void main(String[] args) {
		SpringApplication.run(DemoConsulApplication.class, args);
	}
}

結果

name: srping redis config: RedisConfig{url='localhost', port=6380, timeOut=5000}

結論

以@Value形式獲取配置中心資料,修改配置中心檔案後不能立即生效,需要重啟應用程式伺服器;而使用ConfigurationProperties形式,則能立即生效