zookeeper配置中心
使用zookeeper配置中心
依赖
// cloud版本
// mavenBom 'org.springframework.cloud:spring-cloud-dependencies:2021.0.4'
// mavenBom 'com.alibaba.cloud:spring-cloud-alibaba-dependencies:2021.0.4.0'
dependencies {
implementation("org.springframework.boot:spring-boot-starter-web")
implementation("org.springframework.cloud:spring-cloud-starter-bootstrap")
// 配置中心
implementation("org.springframework.cloud:spring-cloud-starter-zookeeper-config")
}
环境准备
spring.factories
spring.factories
中配置的BootstrapConfiguration类springboot会优先处理
org.springframework.cloud.bootstrap.BootstrapConfiguration=\
aa.slkIE.cloud.zookeeper.AppBootstrapConfiguration
AppBootstrapConfiguration
/**
* 注入zookeeper连接、注入自定义的属性源
*/
public class AppBootstrapConfiguration {
public static CuratorFramework curatorFramework;
@Bean
public CuratorFramework curatorFramework() {
curatorFramework = CuratorFrameworkFactory
.newClient("127.0.0.1:2181", new RetryNTimes(3, 2000));
curatorFramework.start();
return curatorFramework;
}
/**
* 自定义配置中心属性源(简单模拟,从map中读取属性)
* 常见的配置中心:阿里的nacos,携程的apollo,git。
* 只需要实现PropertySourceLocator接口就能实现配置中心
*
* @return
*/
@Bean
public ConsumerPropertySourceLocator consumerPropertySourceLocator() {
return new ConsumerPropertySourceLocator();
}
@PreDestroy
public void destroy() {
curatorFramework.close();
}
}
CloudZookeeperBootstrap启动类
@SpringBootApplication
public class CloudZookeeperApplication {
public static void main(String[] args) {
ConfigurableApplicationContext ac = SpringApplication.run(CloudZookeeperApplication.class, args);
System.out.println(ac.getEnvironment().getProperty("server.port"));
}
}
bootstrap.properties
spring.application.name=h3
spring.profiles.active=dev
# 去zookeeper的/config/h3节点下寻找配置
spring.cloud.zookeeper.config.root=config
spring.cloud.zookeeper.config.defaultContext=h3
# 环境配置,激活的是dev环境(spring.profiles.active=dev)
# /config/h3分隔符dev
# /config/h3分隔符sit
# /config/h3分隔符uat
# 指定路径与环境之前的 分隔符,用英文逗号分隔
spring.cloud.zookeeper.config.profileSeparator=,
zookeeper配置信息
读取配置的原理概要
ConsumerPropertySourceLocator
:自定义的配置源是一个以map为基础的源,最终通过map.get("")
获取到属性值ZookeeperPropertySourceLocator
:zookeeper的配置源是以curatorFramework
为基础的源,通过curatorFramework.getData().forPath("")
获取属性值
配置刷新原理概要
使用@Refresh
注解
自动刷新原理
- 配置中心监听的数据发生改变后,只需要发布一个事件
RefreshEvent
- spring创建一个新的
applicationContext
从各个配置源获取最新配置 - 加了
@RefreshScope
注解的bean重新绑定属性,完成配置更新