首页 > 其他分享 >Apollo的ConfigUtil

Apollo的ConfigUtil

时间:2023-04-06 15:12:42浏览次数:33  
标签:Apollo return String private ConfigUtil import apollo public

package com.ctrip.framework.apollo.util;

import com.ctrip.framework.apollo.core.ConfigConsts;
import com.ctrip.framework.apollo.core.MetaDomainConsts;
import com.ctrip.framework.apollo.core.enums.Env;
import com.ctrip.framework.apollo.core.enums.EnvUtils;
import com.ctrip.framework.apollo.exceptions.ApolloConfigException;
import com.ctrip.framework.foundation.Foundation;
import com.google.common.base.Strings;
import com.longfor.gaia.gfs.rsa.RSAUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.PrivateKey;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

/**
 * @author Jason Song([email protected])
 */
public class ConfigUtil {
  private static final Logger logger = LoggerFactory.getLogger(ConfigUtil.class);
  private int refreshInterval = 5;
  private TimeUnit refreshIntervalTimeUnit = TimeUnit.MINUTES;
  private int connectTimeout = 1000; //1 second
  private int readTimeout = 5000; //5 seconds
  private String cluster;
  private int loadConfigQPS = 2; //2 times per second
  private int longPollQPS = 2; //2 times per second
  //for on error retry
  private long one rrorRetryInterval = 1;//1 second
  private TimeUnit one rrorRetryIntervalTimeUnit = TimeUnit.SECONDS;//1 second
  //for typed config cache of parser result, e.g. integer, double, long, etc.
  private long maxConfigCacheSize = 500;//500 cache key
  private long configCacheExpireTime = 1;//1 minute
  private TimeUnit configCacheExpireTimeUnit = TimeUnit.MINUTES;//1 minute
  private long longPollingInitialDelayInMills = 2000;//2 seconds
  private boolean autoUpdateInjectedSpringProperties = true;

  private PrivateKey apolloPrivateKey = null;
  public static final String APOLLO_PRIVATE_KEY = "apollo.private.key";
  public static final String DEFAULT_KEY_IN_CLASSPATH = "apollo_private_key";
  private static final String CIPHER_PREFIX = "$#";

  public ConfigUtil() {
    initRefreshInterval();
    initConnectTimeout();
    initReadTimeout();
    initCluster();
    initQPS();
    initMaxConfigCacheSize();
    initLongPollingInitialDelayInMills();
    initAutoUpdateInjectedSpringProperties();
    initApolloPrivateKey();
  }

  /**
   * Get the app id for the current application.
   *
   * @return the app id or ConfigConsts.NO_APPID_PLACEHOLDER if app id is not available
   */
  public String getAppId() {
    String appId = Foundation.app().getAppId();
    if (Strings.isNullOrEmpty(appId)) {
      appId = ConfigConsts.NO_APPID_PLACEHOLDER;
      logger.warn("app.id is not set, please make sure it is set in classpath:/META-INF/app.properties, now apollo " +
          "will only load public namespace configurations!");
    }
    return appId;
  }

  /**
   * Get the data center info for the current application.
   *
   * @return the current data center, null if there is no such info.
   */
  public String getDataCenter() {
    return Foundation.server().getDataCenter();
  }

  private void initCluster() {
    //Load data center from system property
    cluster = System.getProperty(ConfigConsts.APOLLO_CLUSTER_KEY);

    //Use data center as cluster
    if (Strings.isNullOrEmpty(cluster)) {
      cluster = getDataCenter();
    }

    //Use default cluster
    if (Strings.isNullOrEmpty(cluster)) {
      cluster = ConfigConsts.CLUSTER_NAME_DEFAULT;
    }
  }

  /**
   * Get the cluster name for the current application.
   *
   * @return the cluster name, or "default" if not specified
   */
  public String getCluster() {
    return cluster;
  }

  /**
   * Get the current environment.
   *
   * @return the env, UNKNOWN if env is not set or invalid
   */
  public Env getApolloEnv() {
    return EnvUtils.transformEnv(Foundation.server().getEnvType());
  }

  public String getLocalIp() {
    return Foundation.net().getHostAddress();
  }

  public String getMetaServerDomainName() {
    return MetaDomainConsts.getDomain(getApolloEnv());
  }

  private void initConnectTimeout() {
    String customizedConnectTimeout = System.getProperty("apollo.connectTimeout");
    if (!Strings.isNullOrEmpty(customizedConnectTimeout)) {
      try {
        connectTimeout = Integer.parseInt(customizedConnectTimeout);
      } catch (Throwable ex) {
        logger.error("Config for apollo.connectTimeout is invalid: {}", customizedConnectTimeout);
      }
    }
  }

  public int getConnectTimeout() {
    return connectTimeout;
  }

  private void initReadTimeout() {
    String customizedReadTimeout = System.getProperty("apollo.readTimeout");
    if (!Strings.isNullOrEmpty(customizedReadTimeout)) {
      try {
        readTimeout = Integer.parseInt(customizedReadTimeout);
      } catch (Throwable ex) {
        logger.error("Config for apollo.readTimeout is invalid: {}", customizedReadTimeout);
      }
    }
  }

  public int getReadTimeout() {
    return readTimeout;
  }

  private void initRefreshInterval() {
    String customizedRefreshInterval = System.getProperty("apollo.refreshInterval");
    if (!Strings.isNullOrEmpty(customizedRefreshInterval)) {
      try {
        refreshInterval = Integer.parseInt(customizedRefreshInterval);
      } catch (Throwable ex) {
        logger.error("Config for apollo.refreshInterval is invalid: {}", customizedRefreshInterval);
      }
    }
  }

  public int getRefreshInterval() {
    return refreshInterval;
  }

  public TimeUnit getRefreshIntervalTimeUnit() {
    return refreshIntervalTimeUnit;
  }

  private void initQPS() {
    String customizedLoadConfigQPS = System.getProperty("apollo.loadConfigQPS");
    if (!Strings.isNullOrEmpty(customizedLoadConfigQPS)) {
      try {
        loadConfigQPS = Integer.parseInt(customizedLoadConfigQPS);
      } catch (Throwable ex) {
        logger.error("Config for apollo.loadConfigQPS is invalid: {}", customizedLoadConfigQPS);
      }
    }

    String customizedLongPollQPS = System.getProperty("apollo.longPollQPS");
    if (!Strings.isNullOrEmpty(customizedLongPollQPS)) {
      try {
        longPollQPS = Integer.parseInt(customizedLongPollQPS);
      } catch (Throwable ex) {
        logger.error("Config for apollo.longPollQPS is invalid: {}", customizedLongPollQPS);
      }
    }
  }

  public int getLoadConfigQPS() {
    return loadConfigQPS;
  }

  public int getLongPollQPS() {
    return longPollQPS;
  }

  public long getOnErrorRetryInterval() {
    return one rrorRetryInterval;
  }

  public TimeUnit getOnErrorRetryIntervalTimeUnit() {
    return one rrorRetryIntervalTimeUnit;
  }

  public String getDefaultLocalCacheDir() {
    String cacheRoot = getCustomizedCacheRoot();

    if (!Strings.isNullOrEmpty(cacheRoot)) {
      return cacheRoot + File.separator + getAppId();
    }

    cacheRoot = isOSWindows() ? "C:\\opt\\data\\%s" : "/opt/data/%s";
    return String.format(cacheRoot, getAppId());
  }

  private String getCustomizedCacheRoot() {
    // 1. Get from System Property
    String cacheRoot = System.getProperty("apollo.cacheDir");
    if (Strings.isNullOrEmpty(cacheRoot)) {
      // 2. Get from OS environment variable
      cacheRoot = System.getenv("APOLLO_CACHEDIR");
    }
    if (Strings.isNullOrEmpty(cacheRoot)) {
      // 3. Get from server.properties
      cacheRoot = Foundation.server().getProperty("apollo.cacheDir", null);
    }

    return cacheRoot;
  }

  public boolean isInLocalMode() {
    try {
      return Env.LOCAL == getApolloEnv();
    } catch (Throwable ex) {
      //ignore
    }
    return false;
  }

  public boolean isOSWindows() {
    String osName = System.getProperty("os.name");
    if (Strings.isNullOrEmpty(osName)) {
      return false;
    }
    return osName.startsWith("Windows");
  }

  private void initMaxConfigCacheSize() {
    String customizedConfigCacheSize = System.getProperty("apollo.configCacheSize");
    if (!Strings.isNullOrEmpty(customizedConfigCacheSize)) {
      try {
        maxConfigCacheSize = Long.valueOf(customizedConfigCacheSize);
      } catch (Throwable ex) {
        logger.error("Config for apollo.configCacheSize is invalid: {}", customizedConfigCacheSize);
      }
    }
  }

  public long getMaxConfigCacheSize() {
    return maxConfigCacheSize;
  }

  public long getConfigCacheExpireTime() {
    return configCacheExpireTime;
  }

  public TimeUnit getConfigCacheExpireTimeUnit() {
    return configCacheExpireTimeUnit;
  }

  private void initLongPollingInitialDelayInMills() {
    String customizedLongPollingInitialDelay = System.getProperty("apollo.longPollingInitialDelayInMills");
    if (!Strings.isNullOrEmpty(customizedLongPollingInitialDelay)) {
      try {
        longPollingInitialDelayInMills = Long.valueOf(customizedLongPollingInitialDelay);
      } catch (Throwable ex) {
        logger.error("Config for apollo.longPollingInitialDelayInMills is invalid: {}", customizedLongPollingInitialDelay);
      }
    }
  }

  public long getLongPollingInitialDelayInMills() {
    return longPollingInitialDelayInMills;
  }

  private void initAutoUpdateInjectedSpringProperties() {
    // 1. Get from System Property
    String enableAutoUpdate = System.getProperty("apollo.autoUpdateInjectedSpringProperties");
    if (Strings.isNullOrEmpty(enableAutoUpdate)) {
      // 2. Get from app.properties
      enableAutoUpdate = Foundation.app().getProperty("apollo.autoUpdateInjectedSpringProperties", null);
    }
    if (!Strings.isNullOrEmpty(enableAutoUpdate)) {
      autoUpdateInjectedSpringProperties = Boolean.parseBoolean(enableAutoUpdate.trim());
    }
  }

  public boolean isAutoUpdateInjectedSpringPropertiesEnabled() {
    return autoUpdateInjectedSpringProperties;
  }

  private void initApolloPrivateKey() {
    String apolloPrivateKeyStr = "";
    String filePath = System.getProperty(APOLLO_PRIVATE_KEY);
    try {
      if (filePath == null) {
        logger.info("try to find apollo_private_key in classpath");
        try {
          Path path = Paths.get(this.getClass().getClassLoader().getResource(DEFAULT_KEY_IN_CLASSPATH).toURI());
          apolloPrivateKeyStr = new String(Files.readAllBytes(path), Charset.forName("UTF-8"));
        } catch (Exception e) {
          logger.warn("apollo_private_key in classpath not found!");
        }
      } else {
        logger.info("use apollo.private.key:"+ filePath);
        Path path = Paths.get(filePath);
        apolloPrivateKeyStr = new String(Files.readAllBytes(path), Charset.forName("UTF-8"));
      }
      if (!apolloPrivateKeyStr.isEmpty()) {
        apolloPrivateKey = RSAUtil.loadPrivateKey(apolloPrivateKeyStr);
      }
    }catch (IOException e) {
      logger.error("read private key failed!", e);
      throw new ApolloConfigException("read private key failed!", e);
    }catch (Exception e) {
      logger.error("load private key failed!", e);
      throw new ApolloConfigException("load private key failed!", e);
    }
  }

  public PrivateKey getApolloPrivateKey() {
    return apolloPrivateKey;
  }

  public Properties getDecryptProperties(Properties cypherProperties) {
    Properties properties = new Properties();
    properties.putAll(cypherProperties);
    PrivateKey privateKey = getApolloPrivateKey();
    if (privateKey == null) {
      logger.info("private key not found. skip decryption!");
      return properties;
    } else {
      for (Map.Entry<Object, Object> entry: properties.entrySet()) {
        String value = entry.getValue().toString().trim();
        if (value.startsWith(CIPHER_PREFIX)) {
          try {
            String decryptValue = RSAUtil.decrypt(privateKey, value);
            entry.setValue(decryptValue);
          } catch (Exception e) {
            System.err.println("decrypt config failed!");
            e.printStackTrace();
            logger.error("decrypt config failed!", e);
            throw new ApolloConfigException("decrypt config failed!");
          }
        }
      }
      return properties;
    }
  }

}

 

标签:Apollo,return,String,private,ConfigUtil,import,apollo,public
From: https://www.cnblogs.com/tiancai/p/17292808.html

相关文章

  • Springboot整合Apollo配置中心
    前言参考这一篇在Linux部署Apollo配置中心可以搭建出一套Apollo配置中心服务,我们在这里重点看看Springboot如何整合Apollo,将配置交给配置中心管理,并在修改后及时生效到服务上。我们模拟工作中的开发(development,DEV)和生产(production,PRO)两套环境,在下面例子中会实现不同环境下配......
  • 在Linux部署Apollo配置中心
    前言这篇是参考官网文档总结的Apollo分布式部署方式,包含具体步骤、资源和相关脚本,也在必要的地方给出了资料来源。通过Apollo-中文文档-部署架构可以了解到单机、集群和高可用部署架构的最佳实践方式。安装步骤本篇实践是在Linux系统,使用Apollo1.9.1版本为例,要求环境包含......
  • Apollo安装-docker安装
    安装mysql接取mqsql镜像dockerpullmysql:latest创建挂载的目录#mkdir-p/usr/local/docker/mysql/conf#mkdir-p/usr/local/docker/mysql/logs#mkdir-p/usr/l......
  • apollo配置json
    #json串原文[{"username":"李小刚","sex":"男"},{"username":"苗翠花","sex":"女"}]publicclassMyDTO{privateStringusername;privateStringsex;......
  • docker部署Apollo系列(.net Core 连接读取)
    Docker部署Apollo 简单介绍:统一管理不同环境、不同集群的配置Apollo提供了一个统一界面集中式管理不同环境(environment)、不同集群(cluster)、不同命名空间(namespace......
  • ABP微服务系列学习-对接Apollo配置中心
    前面我们把服务都已经成功启动,并且对接前端Angular界面。但是在微服务结构中,多个服务意味着需要配置多个配置文件,这时就需要引入配置中心这玩意了。配置中心有很多现成的方......
  • apollo源码同时兼容mysql、postgresql、oracle解决思路
    本文摘录apollo源码采用的是jpa规范Hibernate进行持久化的ORM框架解决思路:思路一:使用jpa配置文件persistence.xml文件,根据使用的数据库动态加载实体类与数据库中实体......
  • 聊聊如何利用apollo与druid整合实现数据源动态热切
    前言本文的素材来源与某次和朋友技术交流,当时朋友就跟我吐槽说apollo不如nacos好用,而且他们还因为apollo发生过一次线上事故。故事的背景大概是如下前阵子朋友部门的数......
  • apollo 系统出错,请重试或联系系统负责人
    本地测试apollo,使用官方QuickStart方式,启动Apollo配置中心后,访问http://localhost:8070/的portal页面,一直报错:系统出错,请重试或联系系统负责人官方解决方案是:如果提示系统......
  • Apollo实现cron语句的热配置
    GitHub项目地址Gitee项目地址Apollo(阿波罗)是携程框架部门研发的分布式配置中心,能够集中化管理应用不同环境、不同集群的配置,配置修改后能够实时推送到应用端,并且具备规范......