最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java Apollo是如何實現(xiàn)配置更新的

 更新時間:2021年03月02日 16:24:52   作者:雙鬼單帶  
這篇文章主要介紹了Java Apollo是如何實現(xiàn)配置更新的,幫助大家更好的理解和學習使用Java,感興趣的朋友可以了解下

這篇文檔主要關注下配置修改后對應的 Java 對象是如何更新,并不關注整體的配置改動流程

所有代碼都來自 apollo-client 項目

更新流程

在 Apollo 控制臺進行配置修改并發(fā)布后,對應的 client 端拉取到更新后,會調用到 com.ctrip.framework.apollo.spring.property.AutoUpdateConfigChangeListener#onChange 方法

在調用 onChange 會收到對應的修改的配置信息 ConfigChangeEvent, 其中包含改動的 key 和 value, 則改動流程如下:

  1. 根據(jù)改動的配置的 key 從 springValueRegistry 找到對應的關聯(lián)到這個 key 的 Spring Bean 信息,如果找不到則不處理
  2. 根據(jù)找到的 Spring Bean 信息,進行對應關聯(lián)配置的更新

在第二步中會判斷關聯(lián)配置是用過屬性關聯(lián)還是方法進行關聯(lián)的,代碼如下

public void update(Object newVal) throws IllegalAccessException, InvocationTargetException {
  if (isField()) {
    injectField(newVal);
  } else {
    injectMethod(newVal);
  }
}

在上面的問題中,還有兩個問題存疑

  1. 如何通過 key 找到對應的 Spring Bean 信息
  2. 如何將 Apollo 的配置值轉換為 Spring 的識別的值
public class AutoUpdateConfigChangeListener implements ConfigChangeListener{
 private static final Logger logger = LoggerFactory.getLogger(AutoUpdateConfigChangeListener.class);

 private final boolean typeConverterHasConvertIfNecessaryWithFieldParameter;
 private final Environment environment;
 private final ConfigurableBeanFactory beanFactory;
 private final TypeConverter typeConverter;
 private final PlaceholderHelper placeholderHelper;
 private final SpringValueRegistry springValueRegistry;
 private final Gson gson;

 public AutoUpdateConfigChangeListener(Environment environment, ConfigurableListableBeanFactory beanFactory){
  this.typeConverterHasConvertIfNecessaryWithFieldParameter = testTypeConverterHasConvertIfNecessaryWithFieldParameter();
  this.beanFactory = beanFactory;
  this.typeConverter = this.beanFactory.getTypeConverter();
  this.environment = environment;
  this.placeholderHelper = SpringInjector.getInstance(PlaceholderHelper.class);
  this.springValueRegistry = SpringInjector.getInstance(SpringValueRegistry.class);
  this.gson = new Gson();
 }

 @Override
 public void onChange(ConfigChangeEvent changeEvent) {
  Set<String> keys = changeEvent.changedKeys();
  if (CollectionUtils.isEmpty(keys)) {
   return;
  }
  for (String key : keys) {
   // 1. check whether the changed key is relevant
   Collection<SpringValue> targetValues = springValueRegistry.get(beanFactory, key);
   if (targetValues == null || targetValues.isEmpty()) {
    continue;
   }

   // 2. update the value
   for (SpringValue val : targetValues) {
    updateSpringValue(val);
   }
  }
 }

 private void updateSpringValue(SpringValue springValue) {
  try {
   Object value = resolvePropertyValue(springValue);
   springValue.update(value);

   logger.info("Auto update apollo changed value successfully, new value: {}, {}", value,
     springValue);
  } catch (Throwable ex) {
   logger.error("Auto update apollo changed value failed, {}", springValue.toString(), ex);
  }
 }

 /**
  * Logic transplanted from DefaultListableBeanFactory
  * @see org.springframework.beans.factory.support.DefaultListableBeanFactory#doResolveDependency(org.springframework.beans.factory.config.DependencyDescriptor, java.lang.String, java.util.Set, org.springframework.beans.TypeConverter)
  */
 private Object resolvePropertyValue(SpringValue springValue) {
  // value will never be null, as @Value and @ApolloJsonValue will not allow that
  Object value = placeholderHelper
    .resolvePropertyValue(beanFactory, springValue.getBeanName(), springValue.getPlaceholder());

  if (springValue.isJson()) {
   value = parseJsonValue((String)value, springValue.getGenericType());
  } else {
   if (springValue.isField()) {
    // org.springframework.beans.TypeConverter#convertIfNecessary(java.lang.Object, java.lang.Class, java.lang.reflect.Field) is available from Spring 3.2.0+
    if (typeConverterHasConvertIfNecessaryWithFieldParameter) {
     value = this.typeConverter
       .convertIfNecessary(value, springValue.getTargetType(), springValue.getField());
    } else {
     value = this.typeConverter.convertIfNecessary(value, springValue.getTargetType());
    }
   } else {
    value = this.typeConverter.convertIfNecessary(value, springValue.getTargetType(),
      springValue.getMethodParameter());
   }
  }

  return value;
 }

 private Object parseJsonValue(String json, Type targetType) {
  try {
   return gson.fromJson(json, targetType);
  } catch (Throwable ex) {
   logger.error("Parsing json '{}' to type {} failed!", json, targetType, ex);
   throw ex;
  }
 }

 private boolean testTypeConverterHasConvertIfNecessaryWithFieldParameter() {
  try {
   TypeConverter.class.getMethod("convertIfNecessary", Object.class, Class.class, Field.class);
  } catch (Throwable ex) {
   return false;
  }
  return true;
 }
}

如何將配置 key 和 Spring Bean 關聯(lián)起來

在 Spring 常見配置包括 2 種

public class ApiConfig {
 
 	// 1. 直接在 Field 是進行注入
  @Value("${feifei.appId}")
  protected String appId;

  protected String predUrl;

 	// 2. 在方法上進行注入
  @Value("${predUrl}")
  public void setPredUrl(String predUrl) {
    this.predUrl = predUrl;
  }
}

在 Apollo 代碼中,通過實現(xiàn) BeanPostProcessor 接口來檢測所有的Spring Bean 的創(chuàng)建過程,在 Spring Bean 創(chuàng)建的過程中會調用對應的 org.springframework.beans.factory.config.BeanPostProcessor#postProcessBeforeInitialization org.springframework.beans.factory.config.BeanPostProcessor#postProcessAfterInitialization 方法。

Apollo 通過在 Bean 生成過程中,檢測 Bean 類中屬性和方法是否存在 @Value 注解,如果存在,提出其中的 key, 其處理方法在 processFieldprocessMethod 分別處理 Field 和 Method 中可能出現(xiàn)的 @Value 注解。如果存在注解則將對應的信息存到 SpringValue 對應 springValueRegistry 全局對象中,方便在其它地方可以直接獲取。

在屬性除了通過 @Value 注入,也可以用過 xml 進行配置,在這種情況通過 processBeanPropertyValues 方法來處理

通過兩種處理方式就可以將 key 和對應的 Spring Bean 信息關聯(lián)起來

public class SpringValueProcessor extends ApolloProcessor implements BeanFactoryPostProcessor, BeanFactoryAware {

 private static final Logger logger = LoggerFactory.getLogger(SpringValueProcessor.class);

 private final ConfigUtil configUtil;
 private final PlaceholderHelper placeholderHelper;
 private final SpringValueRegistry springValueRegistry;

 private BeanFactory beanFactory;
 private Multimap<String, SpringValueDefinition> beanName2SpringValueDefinitions;

 public SpringValueProcessor() {
  configUtil = ApolloInjector.getInstance(ConfigUtil.class);
  placeholderHelper = SpringInjector.getInstance(PlaceholderHelper.class);
  springValueRegistry = SpringInjector.getInstance(SpringValueRegistry.class);
  beanName2SpringValueDefinitions = LinkedListMultimap.create();
 }

 @Override
 public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
   throws BeansException {
  if (configUtil.isAutoUpdateInjectedSpringPropertiesEnabled() && beanFactory instanceof BeanDefinitionRegistry) {
   beanName2SpringValueDefinitions = SpringValueDefinitionProcessor
     .getBeanName2SpringValueDefinitions((BeanDefinitionRegistry) beanFactory);
  }
 }

 @Override
 public Object postProcessBeforeInitialization(Object bean, String beanName)
   throws BeansException {
  if (configUtil.isAutoUpdateInjectedSpringPropertiesEnabled()) {
   super.postProcessBeforeInitialization(bean, beanName);
   processBeanPropertyValues(bean, beanName);
  }
  return bean;
 }


 @Override
 protected void processField(Object bean, String beanName, Field field) {
  // register @Value on field
  Value value = field.getAnnotation(Value.class);
  if (value == null) {
   return;
  }
  Set<String> keys = placeholderHelper.extractPlaceholderKeys(value.value());

  if (keys.isEmpty()) {
   return;
  }

  for (String key : keys) {
   SpringValue springValue = new SpringValue(key, value.value(), bean, beanName, field, false);
   springValueRegistry.register(beanFactory, key, springValue);
   logger.debug("Monitoring {}", springValue);
  }
 }

 @Override
 protected void processMethod(Object bean, String beanName, Method method) {
  //register @Value on method
  Value value = method.getAnnotation(Value.class);
  if (value == null) {
   return;
  }
  //skip Configuration bean methods
  if (method.getAnnotation(Bean.class) != null) {
   return;
  }
  if (method.getParameterTypes().length != 1) {
   logger.error("Ignore @Value setter {}.{}, expecting 1 parameter, actual {} parameters",
     bean.getClass().getName(), method.getName(), method.getParameterTypes().length);
   return;
  }

  Set<String> keys = placeholderHelper.extractPlaceholderKeys(value.value());

  if (keys.isEmpty()) {
   return;
  }

  for (String key : keys) {
   SpringValue springValue = new SpringValue(key, value.value(), bean, beanName, method, false);
   springValueRegistry.register(beanFactory, key, springValue);
   logger.info("Monitoring {}", springValue);
  }
 }


 private void processBeanPropertyValues(Object bean, String beanName) {
  Collection<SpringValueDefinition> propertySpringValues = beanName2SpringValueDefinitions
    .get(beanName);
  if (propertySpringValues == null || propertySpringValues.isEmpty()) {
   return;
  }

  for (SpringValueDefinition definition : propertySpringValues) {
   try {
    PropertyDescriptor pd = BeanUtils
      .getPropertyDescriptor(bean.getClass(), definition.getPropertyName());
    Method method = pd.getWriteMethod();
    if (method == null) {
     continue;
    }
    SpringValue springValue = new SpringValue(definition.getKey(), definition.getPlaceholder(),
      bean, beanName, method, false);
    springValueRegistry.register(beanFactory, definition.getKey(), springValue);
    logger.debug("Monitoring {}", springValue);
   } catch (Throwable ex) {
    logger.error("Failed to enable auto update feature for {}.{}", bean.getClass(),
      definition.getPropertyName());
   }
  }

  // clear
  beanName2SpringValueDefinitions.removeAll(beanName);
 }

 @Override
 public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
  this.beanFactory = beanFactory;
 }
}

以上就是Java Apollo是如何實現(xiàn)配置更新的的詳細內容,更多關于Java Apollo 配置更新的資料請關注腳本之家其它相關文章!

相關文章

  • SpringBoot之自定義啟動異常堆棧信息打印方式

    SpringBoot之自定義啟動異常堆棧信息打印方式

    這篇文章主要介紹了SpringBoot之自定義啟動異常堆棧信息打印方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-08-08
  • springboot2.5.6集成RabbitMq實現(xiàn)Topic主題模式(推薦)

    springboot2.5.6集成RabbitMq實現(xiàn)Topic主題模式(推薦)

    這篇文章主要介紹了springboot2.5.6集成RabbitMq實現(xiàn)Topic主題模式(推薦),pom.xml引入依賴和常量類創(chuàng)建,本文通過實例代碼給大家介紹的非常詳細,需要的朋友參考下吧
    2021-11-11
  • 簡單了解JAVA NIO

    簡單了解JAVA NIO

    這篇文章主要介紹了JAVA NIO的的相關資料,文中講解非常細致,幫助大家更好的理解和學習,感興趣的朋友可以了解下
    2020-07-07
  • springboot使用war包部署到外部tomcat過程解析

    springboot使用war包部署到外部tomcat過程解析

    這篇文章主要介紹了springboot使用war包部署到外部tomcat過程解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-01-01
  • SSM?Mapper文件查詢出返回數(shù)據(jù)查不到個別字段的問題

    SSM?Mapper文件查詢出返回數(shù)據(jù)查不到個別字段的問題

    這篇文章主要介紹了SSM?Mapper文件查詢出返回數(shù)據(jù)查不到個別字段的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-01-01
  • Java中JDBC的使用教程詳解

    Java中JDBC的使用教程詳解

    Java語言操作數(shù)據(jù)庫?JDBC本質:其實是官方(sun公司)定義的一套操作所有關系型數(shù)據(jù)庫的規(guī)則,即接口。本文講解了JDBC的使用方法,需要的可以參考一下
    2022-06-06
  • java中transient關鍵字用法分析

    java中transient關鍵字用法分析

    這篇文章主要介紹了java中transient關鍵字用法,以實例形式分析了java中transient關鍵字的功能及使用技巧,具有一定參考借鑒價值,需要的朋友可以參考下
    2015-02-02
  • Spring?Boot?Actuator管理日志的實現(xiàn)

    Spring?Boot?Actuator管理日志的實現(xiàn)

    本文主要介紹了Spring?Boot?Actuator管理日志的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2022-07-07
  • 深入解析Spring Cloud內置的Zuul過濾器

    深入解析Spring Cloud內置的Zuul過濾器

    這篇文章主要給大家深入的介紹了Spring Cloud內置的Zuul過濾器的相關資料,文中給大家介紹的很詳細,相信對大家具有一定的參考價值,需要的朋友們下面來一起看看吧。
    2017-02-02
  • Java數(shù)字簽名算法DSA實例詳解

    Java數(shù)字簽名算法DSA實例詳解

    這篇文章主要介紹了Java數(shù)字簽名算法DSA,結合實例形式分析了Java數(shù)字簽名算法DSA具體定義與使用技巧,需要的朋友可以參考下
    2018-05-05

最新評論

文昌市| 牙克石市| 周口市| 定西市| 芜湖市| 章丘市| 威远县| 嘉黎县| 东兴市| 喜德县| 巴东县| 于都县| 神池县| 中宁县| 灌阳县| 威海市| 周口市| 安泽县| 志丹县| 铜鼓县| 饶河县| 册亨县| 枞阳县| 汝州市| 长治县| 澄迈县| 通化市| 剑河县| 射阳县| 革吉县| 安塞县| 新邵县| 温宿县| 简阳市| 乾安县| 神农架林区| 抚远县| 苍山县| 盐亭县| 刚察县| 河间市|