手写分布式配置中心(六)整合springboot(自动刷新)

对于springboot配置自动刷新,原理也很简单,就是在启动过程中用一个BeanPostProcessor去收集需要自动刷新的字段,然后在springboot启动后开启轮询任务即可。
不过需要对之前的代码再次做修改,因为springboot的配置注入@value("${}"),允许多个${}和嵌套,所以不能确定简单的确定用到了那个配置,本文为了简单就把所有的配置都认为需要动态刷新,实际用的时候可以在application.yml中配置需要动态刷新的配置id列表。代码在https://gitee.com/summer-cat001/config-center。其中设计到的原理都在之前的一篇文章中,感兴趣可以去看看springboot配置注入增强(二)属性注入的原理_springboot bean属性增强-CSDN博客

新增注解

@Target({ElementType.FIELD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ConfigRefresh {
}

加上这个注解的字段并且字段上有@value注解就会自动刷新

收集自动刷新的字段

这里会收集自动刷新的字段,并加到ConfigCenterClient的refreshFieldValueList中。长轮询会从这里取数据进行对比,如果发生变化就更新bean中的字段

@Slf4j
public class ConfigRefreshAnnotationBeanPostProcessor implements ApplicationRunner, BeanPostProcessor, BeanFactoryAware, EnvironmentAware {private Environment environment;private ConfigurableBeanFactory beanFactory;@Overridepublic void setBeanFactory(BeanFactory beanFactory) throws BeansException {if (!(beanFactory instanceof ConfigurableBeanFactory)) {log.warn("ConfigurableBeanFactory requires a ConfigurableListableBeanFactory");return;}this.beanFactory = (ConfigurableBeanFactory) beanFactory;}@Overridepublic Object postProcessBeforeInitialization(Object bean, final String beanName) throws BeansException {if (beanFactory != null) {ReflectionUtils.doWithFields(bean.getClass(), field -> {try {ConfigRefresh configRefresh = AnnotationUtils.getAnnotation(field, ConfigRefresh.class);if (configRefresh == null) {return;}Value valueAnnotation = AnnotationUtils.getAnnotation(field, Value.class);if (valueAnnotation == null) {return;}String value = valueAnnotation.value();String relValue = beanFactory.resolveEmbeddedValue(value);ConfigCenterClient configCenterClient = ConfigCenterClient.getInstance(null);configCenterClient.addRefreshFieldValue(bean, field, relValue);} catch (Exception e) {log.error("set bean field fail,beanName:{},fieldName:{}", bean.getClass().getName(), field.getName(), e);}});}return bean;}@Overridepublic void setEnvironment(Environment environment) {this.environment = environment;}@Overridepublic void run(ApplicationArguments args) {ConfigCenterClient configCenterClient = ConfigCenterClient.getInstance(null);configCenterClient.startSpringBootLongPolling((ConfigurableEnvironment) environment, beanFactory);}
}

把该bean注入到springboot中,即在spring.factories中加入自动注入

org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.config.center.autoconfigure.ConfigAutoConfiguration

这是一个ImportSelector会自动注入返回的类

@Import(ConfigAutoConfiguration.class)
public class ConfigAutoConfiguration implements ImportSelector {@Overridepublic String[] selectImports(AnnotationMetadata importingClassMetadata) {return new String[]{ConfigRefreshAnnotationBeanPostProcessor.class.getName()};}
}

启动长轮询

springboot启动完成后会发一个ApplicationRunner事件,我们只要在实现这个接口的bean中启动即可

@Overridepublic void run(ApplicationArguments args) {ConfigCenterClient configCenterClient = ConfigCenterClient.getInstance(null);configCenterClient.startSpringBootLongPolling((ConfigurableEnvironment) environment, beanFactory);}
    public void startSpringBootLongPolling(ConfigurableEnvironment environment, ConfigurableBeanFactory beanFactory) {if (configMap.isEmpty() || refreshFieldValueList.isEmpty()) {log.info("configMap.size:{} refreshFieldValueList.size:{}", configMap.size(), refreshFieldValueList.size());return;}MutablePropertySources propertySources = environment.getPropertySources();MapPropertySource configCenter = (MapPropertySource) propertySources.get(PROPERTY_SOURCE_NAME);if (configCenter == null) {log.warn("configCenter is null");return;}Map<String, Object> source = configCenter.getSource();Thread thread = new Thread(() -> {while (!Thread.interrupted()) {try {Map<String, Integer> configIdMap = configMap.values().stream().collect(Collectors.toMap(c -> c.getId() + "", ConfigBO::getVersion));HttpRespBO httpRespBO = HttpUtil.httpPostJson(url + "/config/change/get/long", JSON.toJSONString(configIdMap), 30000);List<ConfigVO> configList = httpResp2ConfigVOList(httpRespBO);if (configList.isEmpty()) {continue;}configList.forEach(configVO -> {Map<String, Object> result = new HashMap<>();DataTransUtil.buildFlattenedMap(result, configVO.getConfigData(), "");ConfigBO configBO = this.configMap.get(configVO.getId());configBO.setVersion(configVO.getVersion());List<ConfigDataBO> configDataList = configBO.getConfigDataList();Map<String, ConfigDataBO> configDataMap = configDataList.stream().collect(Collectors.toMap(ConfigDataBO::getKey, Function.identity()));result.forEach((key, value) -> {ConfigDataBO configDataBO = configDataMap.get(key);if (configDataBO == null) {configDataList.add(new ConfigDataBO(key, value.toString()));} else {configDataBO.setValue(value.toString());source.put(key, value);}});});refreshFieldValueList.forEach(refreshFieldBO -> {try {Field field = refreshFieldBO.getField();Value valueAnnotation = AnnotationUtils.getAnnotation(field, Value.class);if (valueAnnotation == null) {return;}String value = valueAnnotation.value();String relValue = beanFactory.resolveEmbeddedValue(value);if(relValue.equals(refreshFieldBO.getValue())){return;}field.setAccessible(true);field.set(refreshFieldBO.getBean(), relValue);} catch (Exception e) {log.error("startSpringBootLongPolling set Field error", e);}});} catch (Exception e) {log.error("startSpringBootLongPolling error", e);}}});thread.setName("startSpringBootLongPolling");thread.setDaemon(true);thread.start();}

效果

@Value

@Data
@Component
public class ConfigTest {@ConfigRefresh@Value("${user.name}")private String name;}
    @Autowiredprivate ConfigTest configTest;@Testpublic void configTest() throws InterruptedException {while (true) {System.out.println(configTest.getName());Thread.sleep(1000);}}

@ConfigurationProperties

增加同时有@ConfigurationProperties和@ConfigRefresh的收集

ConfigRefresh configRefresh = AnnotationUtils.findAnnotation(bean.getClass(), ConfigRefresh.class);if (configRefresh != null) {ConfigurationProperties configurationProperties = AnnotationUtils.findAnnotation(bean.getClass(), ConfigurationProperties.class);if (configurationProperties != null) {ConfigCenterClient configCenterClient = ConfigCenterClient.getInstance(null);configCenterClient.addRefreshBeanList(bean);}}

在长轮询的返回中对@ConfigurationProperties重新绑定

refreshBeanList.forEach(refreshBean -> {ConfigurationProperties configurationProperties = AnnotationUtils.findAnnotation(refreshBean.getClass(), ConfigurationProperties.class);if (configurationProperties == null) {log.warn("refreshBeanList refreshBean configurationProperties is null, class:{}", refreshBean.getClass());return;}Binder binder = Binder.get(environment);binder.bind(configurationProperties.prefix(), Bindable.ofInstance(refreshBean));});

完整代码

@Slf4j
public class ConfigRefreshAnnotationBeanPostProcessor implements ApplicationRunner, BeanPostProcessor, BeanFactoryAware, EnvironmentAware {private Environment environment;private ConfigurableBeanFactory beanFactory;@Overridepublic void setBeanFactory(BeanFactory beanFactory) throws BeansException {if (!(beanFactory instanceof ConfigurableBeanFactory)) {log.warn("ConfigurableBeanFactory requires a ConfigurableListableBeanFactory");return;}this.beanFactory = (ConfigurableBeanFactory) beanFactory;}@Overridepublic Object postProcessBeforeInitialization(Object bean, final String beanName) throws BeansException {if (beanFactory != null) {ReflectionUtils.doWithFields(bean.getClass(), field -> {try {ConfigRefresh configRefresh = AnnotationUtils.getAnnotation(field, ConfigRefresh.class);if (configRefresh == null) {return;}Value valueAnnotation = AnnotationUtils.getAnnotation(field, Value.class);if (valueAnnotation == null) {return;}String value = valueAnnotation.value();String relValue = beanFactory.resolveEmbeddedValue(value);ConfigCenterClient configCenterClient = ConfigCenterClient.getInstance(null);configCenterClient.addRefreshFieldValue(bean, field, relValue);} catch (Exception e) {log.error("set bean field fail,beanName:{},fieldName:{}", bean.getClass().getName(), field.getName(), e);}});ConfigRefresh configRefresh = AnnotationUtils.findAnnotation(bean.getClass(), ConfigRefresh.class);if (configRefresh != null) {ConfigurationProperties configurationProperties = AnnotationUtils.findAnnotation(bean.getClass(), ConfigurationProperties.class);if (configurationProperties != null) {ConfigCenterClient configCenterClient = ConfigCenterClient.getInstance(null);configCenterClient.addRefreshBeanList(bean);}}}return bean;}@Overridepublic void setEnvironment(Environment environment) {this.environment = environment;}@Overridepublic void run(ApplicationArguments args) {ConfigCenterClient configCenterClient = ConfigCenterClient.getInstance(null);configCenterClient.startSpringBootLongPolling((ConfigurableEnvironment) environment, beanFactory);}
}
 public void startSpringBootLongPolling(ConfigurableEnvironment environment, ConfigurableBeanFactory beanFactory) {if (configMap.isEmpty() || refreshFieldValueList.isEmpty()) {log.info("configMap.size:{} refreshFieldValueList.size:{}", configMap.size(), refreshFieldValueList.size());return;}MutablePropertySources propertySources = environment.getPropertySources();MapPropertySource configCenter = (MapPropertySource) propertySources.get(PROPERTY_SOURCE_NAME);if (configCenter == null) {log.warn("configCenter is null");return;}Map<String, Object> source = configCenter.getSource();Thread thread = new Thread(() -> {while (!Thread.interrupted()) {try {Map<String, Integer> configIdMap = configMap.values().stream().collect(Collectors.toMap(c -> c.getId() + "", ConfigBO::getVersion));HttpRespBO httpRespBO = HttpUtil.httpPostJson(url + "/config/change/get/long", JSON.toJSONString(configIdMap), 30000);List<ConfigVO> configList = httpResp2ConfigVOList(httpRespBO);if (configList.isEmpty()) {continue;}configList.forEach(configVO -> {Map<String, Object> result = new HashMap<>();DataTransUtil.buildFlattenedMap(result, configVO.getConfigData(), "");ConfigBO configBO = this.configMap.get(configVO.getId());configBO.setVersion(configVO.getVersion());List<ConfigDataBO> configDataList = configBO.getConfigDataList();Map<String, ConfigDataBO> configDataMap = configDataList.stream().collect(Collectors.toMap(ConfigDataBO::getKey, Function.identity()));result.forEach((key, value) -> {ConfigDataBO configDataBO = configDataMap.get(key);if (configDataBO == null) {configDataList.add(new ConfigDataBO(key, value.toString()));} else {configDataBO.setValue(value.toString());source.put(key, value);}});});refreshFieldValueList.forEach(refreshFieldBO -> {try {Field field = refreshFieldBO.getField();Value valueAnnotation = AnnotationUtils.getAnnotation(field, Value.class);if (valueAnnotation == null) {return;}String value = valueAnnotation.value();String relValue = beanFactory.resolveEmbeddedValue(value);if (relValue.equals(refreshFieldBO.getValue())) {return;}field.setAccessible(true);field.set(refreshFieldBO.getBean(), relValue);} catch (Exception e) {log.error("startSpringBootLongPolling set Field error", e);}});refreshBeanList.forEach(refreshBean -> {ConfigurationProperties configurationProperties = AnnotationUtils.findAnnotation(refreshBean.getClass(), ConfigurationProperties.class);if (configurationProperties == null) {log.warn("refreshBeanList refreshBean configurationProperties is null, class:{}", refreshBean.getClass());return;}Binder binder = Binder.get(environment);binder.bind(configurationProperties.prefix(), Bindable.ofInstance(refreshBean));});} catch (Exception e) {log.error("startSpringBootLongPolling error", e);}}});thread.setName("startSpringBootLongPolling");thread.setDaemon(true);thread.start();}

效果

@Component
@ConfigRefresh
@ConfigurationProperties(prefix = "user")
public class ConfigTest2 {private String name;private int age;private List<String> education;public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public List<String> getEducation() {return education;}public void setEducation(List<String> education) {this.education = education;}
}
   @Autowiredprivate ConfigTest2 configTest2;@Testpublic void configTest() throws InterruptedException {while (true) {System.out.println(configTest2.getName() + "-" + configTest2.getAge() + "-" + configTest2.getEducation());Thread.sleep(1000);}}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/521992.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Unity 给刚体一个力或速度

创建平面和小球&#xff0c;给力或给速度让其弹起 给小球挂载刚体&#xff08;Rigibdody&#xff09;和脚本 &#xff08;力是累计或者衰减的&#xff0c;直接给速度就是赋值&#xff0c;但如果速度就和力类似了&#xff09; using System.Collections; using System.Collect…

数据库(mysql)-新手笔记(主外键,视图)

主外键 主键(唯一性,非空性) 主键是数据库表中的一个或多个字段&#xff0c;其值唯一标识表中的每一行/记录。 唯一性: 主键字段中的每个值都必须是唯一的&#xff0c;不能有两个或更多的记录具有相同的主键值 非空性&#xff1a;主键字段不能包含NULL值。 外键(引用完整 …

鸿蒙Harmony应用开发—ArkTS声明式开发(基础手势:Marquee)

跑马灯组件&#xff0c;用于滚动展示一段单行文本。仅当文本内容宽度超过跑马灯组件宽度时滚动&#xff0c;不超过时不滚动。 说明&#xff1a; 该组件从API Version 8开始支持。后续版本如有新增内容&#xff0c;则采用上角标单独标记该内容的起始版本。 子组件 无 接口 Ma…

Python笔记|基础算数运算+数字类型(1)

重新整理记录一下python的基础知识 基础运算符 、-、*、/ &#xff1b;括号 ()用来分组。 >>>2 2 4 >>>50 - 5*6 20 >>>(50 - 5*6) / 4 5.0 >>>8 / 5 1.6向下取整除法&#xff1a;向下舍入到最接近的整数的数学除法。运算符是 //。比如1…

AI大模型,掀起新一波智能浪潮!

AI大模型的出现&#xff0c;标志着人工智能技术迈入了一个新的阶段。这些巨大的模型不仅在规模上超越了以往任何其他人工智能系统&#xff0c;而且在性能上也取得了巨大的突破。由于其庞大的参数量和复杂的结构&#xff0c;AI大模型在各个领域展现出了强大的学习能力和推理能力…

代码随想录算法训练营第day10|232.用栈实现队列、 225. 用队列实现栈

目录 a.232.用栈实现队列 b. 225. 用队列实现栈 a.232.用栈实现队列 题目链接 请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作&#xff08;push、pop、peek、empty&#xff09;&#xff1a; 实现 MyQueue 类&#xff1a; void push(int x) 将元素…

Linux系统——Haproxy高性能负载均衡软件

目录 一、Haproxy介绍 1.Haproxy定义 2.Haproxy主要特性 二、安装Haproxy 1.yum安装 2.第三方rpm包安装 3.编译安装 3.1解决Lua环境 3.2编译安装Haproxy 三、配置文件详解 1.状态页 2.日志管理 2.1定义日志到其他主机站点 3.指定进程线程个数 4.cpu亲缘性 5.多进…

测试框架到底是什么,如何定义?

测试框架的关键组件是什么&#xff1f; 测试执行引擎&#xff1a;协调测试的运行、管理序列和报告结果。 测试脚本存储库&#xff1a;存储将要执行的实际测试用例或脚本。 测试数据&#xff1a;测试执行所需的输入数据&#xff0c;可以是静态的、动态的或动态生成的。 存根和…

【Kafka系列 07】Kafka 如何保证消息不丢失

一、Kafka 消息不丢失的边界 一直以来&#xff0c;很多人对于 Kafka 丢失消息这件事情都有着自己的理解&#xff0c;因而也就有着自己的解决之道。在讨论具体的应对方法之前&#xff0c;我觉得我们首先要明确&#xff0c;在 Kafka 的世界里什么才算是消息丢失&#xff0c;或者…

赛灵思MPSOC实现DP显示(ARM裸机)

一、硬件搭建 此处简单略过一下&#xff0c;在vivado中按照硬件设计进行连线即可。我的vivadoy硬件设计如下&#xff1a; 二、vitis 中的实现 此处使用了AMD赛灵思官方提供的示例程序。具体流程如下&#xff1a; 1、使用vivado中生成的XSA文件&#xff0c;在vitis中建立platfor…

day38 动态规划part1

509. 斐波那契数 简单 斐波那契数 &#xff08;通常用 F(n) 表示&#xff09;形成的序列称为 斐波那契数列 。该数列由 0 和 1 开始&#xff0c;后面的每一项数字都是前面两项数字的和。也就是&#xff1a; F(0) 0&#xff0c;F(1) 1 F(n) F(n - 1) F(n - 2)&#xff0c;…

git分布式管理-头歌实验合并远程分支、rebase、储藏

一、合并远程分支merge 任务描述 在软件开发中&#xff0c;通常会在版本库中创建多个不同的分支进行开发。例如&#xff0c;最基本的可以有一个测试版分支和一个正式版分支&#xff0c;其中测试版分支用来完成最新功能代码的开发与测试&#xff0c;正式版则用于管理即将发布的版…