0%

consul【结合spring cloud使用consul配置中心并自动刷新】

重点:

consul的配置需要全部写在resource目录下bootstrap.yml文件中,写在application.yml中不能生效!

consul config配置

#bootstrap.yml配置
spring:
  cloud:
    consul:
      host: 192.168.1.11
      port: 8500
      config:
        enabled: true
        format: KEY_VALUE
        data-key: data
        watch:
          enabled: true
        prefix: deriii
        acl-token: bd63ce16-ccd0-22e1-d37d-fb948232cbf5
      discovery:
        healthCheckPath: /actuator/health
        healthCheckInterval: 15s
        acl-token: bd63ce16-ccd0-22e1-d37d-fb948232cbf5
        prefer-ip-address: true
        ip-address: 192.168.1.113

获取配置

    //data在consul中完整的目录是prefix + application name + data  
    @Value("${data}")
    String test;
 
    @RequestMapping("/test")
    public String test() {
        return test;
    }

实时刷新,需要在类上加注解

@RefreshScope

另一种实现配置刷新

#bootstrap.yml配置,主要是修改了format为YAML,配合spring boot Configuration使用
spring:
  cloud:
    consul:
      host: 192.168.1.11
      port: 8500
      config:
        enabled: true
        format: YAML
        data-key: data
        watch:
          enabled: true
        prefix: deriiiii
        acl-token: bd63ce16-ccd0-22e1-d37d-fb948232cbf5
      discovery:
        healthCheckPath: /actuator/health
        healthCheckInterval: 15s
        acl-token: bd63ce16-ccd0-22e1-d37d-fb948232cbf5
        prefer-ip-address: true
        ip-address: 192.168.1.113

spring boot 配置类

@ConfigurationProperties(prefix = "ttt")
@Configuration
public class HiConfig {
 
    private String test;
 
    //getter setter ...
}

consul中key为prefix + application Name + data,value为yaml类型,且前缀是ttt,属性名为test

#key = deriiii/service-hello/data
ttt:
 test: asdas

启动类加上

@EnableConfigurationProperties({HiConfig.class})