导读:当应用的配置多了之后,往往需要配置中心来管理配置的生命周期,例如修改、发布、版本管理、回滚、多集群管理等。另外也经常遇到需要动态下发配置的场景,例如开关、业务参数等等。本文主要介绍 Spring Cloud Tencent 如何集成北极星配置中心。
Github 地址: Spring Cloud Tencent
模块简介
配置中心模块是 Spring Cloud Tencent 最核心的模块之一,实现了 Spring Cloud PropertySourceLoader SPI 接口(PolarisConfigFileLocator.java)。
在应用启动 Bootstrap 阶段,Spring Cloud 会调用 PolarisConfigFileLocator 从 Polaris 服务端获取配置文件并加载到 Spring 上下文里。通过 Spring Boot 标准的
@Value
,@ConfigurationProperties
注解即可获取配置内容。
动态配置刷新能力,则通过 Spring Cloud 标准的 @RefreshScope
机制实现。
注意: 由于 Spring Cloud PropertySourceLoader SPI 是在 Bootstrap 阶段调用,所以 Polaris Config 相关的配置内容(例如Polaris 服务地址)需要放在 bootstrap.yml 文件里,而不能放在 application.yml 文件里,否则会初始化失败。
快速入门
本章节将介绍如何在 Spring Cloud 项目中使用 Spring Cloud Tencent Config 的功能。
完整 Example 代码请参考:polaris-config-example
第一步:引入 Polaris 服务端
方式一:搭建本地北极星服务
搭建北极星服务请参考 Polaris Getting Started
方式二:使用北极星开源提供的体验环境
- Console Address : http://14.116.241.63:8080/
- Username: polaris
- Password: polaris
- Server Address:
grpc://183.47.111.80:8091
方式三:使用腾讯云北极星服务
腾讯云提供了免运维的北极星云服务,基于云服务可以快速开通生产级高可用北极星集群 了解更多
第二步:引入 Spring Cloud Tencent Config 依赖
- 参考 Spring Cloud Tencent 版本管理 文档获取最新的版本号,引入 Spring Cloud Tencent Bom,例如:
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.tencent.cloud</groupId>
<artifactId>spring-cloud-tencent-dependencies</artifactId>