SpringBoot配置中心

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重新绑定属性,完成配置更新
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值