Spring Cloud Tencent Config学习笔记

Java版本: 1.8

Spring Boot版本:2.3.2.RELEASE

Spring Cloud Tencent版本:1.5.3-Hoxton.SR9

在应用服务pom文件中引入北极星配置文件jar包,同时也需引入北极星服务发现jar包。

这样在北极星(polaris)服务台配置的配置文件即可被读取(配置中心-配置分组-命名空间-配置文件)

<!--北极星服务发现jar包-->
<dependency>
    <groupId>com.tencent.cloud</groupId>
    <artifactId>spring-cloud-starter-tencent-polaris-discovery</artifactId>
</dependency>
<!--北极星配置中心jar包-->
<dependency>
    <groupId>com.tencent.cloud</groupId>
    <artifactId>spring-cloud-starter-tencent-polaris-config</artifactId>
</dependency>

由于 Spring Cloud PropertySourceLoader SPI 是在 Bootstrap 阶段调用,

所以 Polaris Config 相关的配置内容(例如Polaris 服务地址)需要放在 bootstrap.yml 文件里,

而不能放在 application.yml 文件里,否则会初始化失败。

应用服务中调用北极星配置文件(bootstrap.yml):

server:
  session-timeout: 1800
  port: 8083
spring:
  application:
    name: ServerA
  cloud:
    tencent:
      metadata:
        content:
          env: green
    polaris:
      address: grpc://127.0.0.1:8091
      namespace: default                    # 注册在北极星控制台的命名空间名称
      config:
        address: grpc://127.0.0.1:8093      # 选填,只有在配置中心和注册中心是两个不同的地址时才需要配置
        auto-refresh: true                  # 选填,当配置发布后,动态刷新 Spring 上下文,默认值为 true面
        groups:
          - name: configa                   # 配置分组的名称
            files: [ "application.yml" ]    # 配置文件的名称
teacher:
  name: "bootstrap-inlin"
  age: 20

服务启动类(ServerAApplication):

@SpringBootApplication
public class ServerAApplication {

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

即使不使用配置文件时,spring cloud tencent还是会默认去搜寻服务文件夹下是否存在相关的配置文件:

spring-cloud-tencent:                      #配置文件默认加载顺序
application-${activeProfile}.properties
application-${activeProfile}.yml
application.properties
application.yml
bootstrap-${activeProfile}.properties
bootstrap-${activeProfile}.yml
bootstrap.properties
bootstrap.yml
#优先级从上到下依次降低

接口获取配置参数的方法:

调用接口类(ServeraController):

@RestController
@RequestMapping("/servera")
public class ServeraController {

    private static Logger LOG = LoggerFactory.getLogger(ServeraController.class);

    @Value("${server.port:0}")
    private int port;

    @Value("${teacher.name}")                        //通过 @Value 方式注入获取北极星控制台配置文件的指定属性
    private String tName;

    @Autowired
    PolarisPropertySourceManager polarisPropertySourceManager;  //北极星配置管理类

    @GetMapping("/info")
    public int info(@RequestHeader(value = "ak",required = false) String ak) throws InterruptedException {
        if(!ObjectUtils.isEmpty(ak) && ak.contains("aaa")){
            Thread.sleep(3000);
        }
        LOG.info("Gateway Example Callee [{}] is called.", port);
        return port;
    }
    //测试是否能成功获取北极星控制台的参数
    @GetMapping("/getName")
    public String gettName(){
        List<PolarisPropertySource> allPropertySources = polarisPropertySourceManager.getAllPropertySources();
        return tName;
    }
}

北极星控制台的配置文件:(ServerA-application.yml)

北极星配置多配置分组时,配置文件加载顺序、实际使用的配置文件

如果项目中未指定配置文件时,框架会默认按顺序去寻找当前服务是否存在配置文件(application.properties、application.yml、

bootstrap.properties、bootstrap.yml),有则加载该配置文件,无则略过。

此时,服务中bootstrap.yml配置文件如下:

1、当创建与服务名相同分组的配置文件,从默认的配置文件中获取配置的参数(ServerA-application.yml)

2、当控制台未添加服务名级别的配置文件时,引用bootstrap中指定的配置文件(configa-application.yml)

在多个配置文件同时配置一个key属性时,Polaris会先加载当前服务的配置类。

ServerA:配置文件 configa:配置文件

有关源码的一些东西:

获取加载配置文件框架源码的位置:

jar包位置:spring-cloud-starter-tencent-polaris-config

包名位置: adapter

类名: PolarisConfigFileLocator()

方法名: getInternalConfigFiles

在应用启动 Bootstrap 阶段,Spring Cloud 会调用 PolarisConfigFileLocator 从 Polaris 服务端获取配置文件并加载到 Spring 上下文里。

通过 Spring Boot 标准的 @Value,@ConfigurationProperties 注解即可获取配置内容。

北极星配置中心原理介绍

完整的配置参数

配置项Key

默认值

是否必填

配置项说明

spring.cloud.polaris.config.enabled

true

是否开启配置模块

spring.cloud.polaris.config.address

北极星服务端地址,可不填。当配置中心和注册中心为不同的地址时候才需要填写

spring.cloud.polaris.config.port

8093

北极星配置中心的端口号,默认为 8093

spring.cloud.polaris.config.auto-refresh

true

是否动态更新配置

spring.cloud.polaris.config.groups

从北极星服务端获取自定义的配置文件

spring.cloud.polaris.config.connect-remote-server

true

是否连接到远程北极星配置中心服务端,当没有网络环境或者无北极星服务端时可关闭

自定义配置监听器 (1.6.0 版本之后支持)

可通过注解@PolarisConfigKVFileChangeListener实现针对指定的配置属性名称或者属性前缀进行监听,配置发生变更时会触发方法回调。

注意:目前只支持 KV 结构的配置文件监听

@Component
public final class PersonConfigChangeListener {

	/**
	 * PolarisConfigKVFileChangeListener Example .
	 * @param event instance of {@link ConfigChangeEvent}
	 */
	@PolarisConfigKVFileChangeListener(interestedKeyPrefixes = "teacher")
	public void onChange(ConfigChangeEvent event) {
		Set<String> changedKeys = event.changedKeys();

		for (String changedKey : changedKeys) {
			System.out.printf("%s = %s \n", changedKey, event.getChange(changedKey));
		}
	}

}

参考文献:Spring Cloud Tencent Config 使用文档


版权声明:本文为sinat_35181608原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。