Apollo(六)-源码解析-本地缓存文件位置

x33g5p2x  于2021-12-20 转载在 其他  
字(5.0k)|赞(0)|评价(0)|浏览(555)

前提

启动ConfigServiceApplication,否则无法拉取配置;

调试代码

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>helloworld</artifactId>
        <groupId>com.ydfind</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>apollo-configuration-demo</artifactId>
    <dependencies>
        <dependency>
            <groupId>com.ctrip.framework.apollo</groupId>
            <artifactId>apollo-client</artifactId>
            <version>1.4.0</version>
        </dependency>
        <!-- 日志相关 -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.11.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-slf4j-impl</artifactId>
            <version>2.11.0</version>
        </dependency>
        <!-- take over jcl -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>1.7.25</version>
        </dependency>
    </dependencies>
</project>

ApolloLocalFileDemo.java

package com.ydfind.apollo;

import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ApolloLocalFileDemo {
    private static final Logger logger = LoggerFactory.getLogger(ApolloLocalFileDemo.class);
    private String DEFAULT_VALUE = "undefined";
    private Config config;

    public ApolloLocalFileDemo() {
        config = ConfigService.getAppConfig();
    }

    private String getConfig(String key) {
        String result = config.getProperty(key, DEFAULT_VALUE);
        logger.info(String.format("Loading key : %s with value: %s", key, result));
        return result;
    }

    public static void main(String[] args){
        System.setProperty("env", "dev");
        System.setProperty("dev_meta", "http://localhost:8080");
        ApolloLocalFileDemo apolloConfigDemo = new ApolloLocalFileDemo();
        apolloConfigDemo.getConfig("timeout");
    }
}

log4j2.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration monitorInterval="60">
  <appenders>
    <Console name="Console" target="SYSTEM_OUT">
      <PatternLayout pattern="[%t]%d %-5p [%c] %m%n"/>
    </Console>
    <Async name="Async" includeLocation="true">
      <AppenderRef ref="Console"/>
    </Async>
  </appenders>
  <loggers>
    <logger name="com.ydfind.apollo" additivity="false" level="DEBUG">
      <AppenderRef ref="Async"/>
    </logger>
    <root level="INFO">
      <AppenderRef ref="Async"/>
    </root>
  </loggers>
</configuration>

app.properties

app.id=100004458

分析源码-缓存目录

Debug相关代码

先打断点确定主要的代码:

详细的函数调用情况如下所示:

配置文件的命名规则

分析源码

代码调用关系:findLocalCacheDir() -> LocalFileConfigRepository.findLocalCacheDir -> ConfigUtil.java

private File findLocalCacheDir() {
    try {
      String defaultCacheDir = m_configUtil.getDefaultLocalCacheDir();
      Path path = Paths.get(defaultCacheDir);
      if (!Files.exists(path)) {
        Files.createDirectories(path);
      }
      if (Files.exists(path) && Files.isWritable(path)) {
     // private static final String CONFIG_DIR = "/config-cache";
      // 默认目录后面会加上/config-cache
        return new File(defaultCacheDir, CONFIG_DIR);
      }
    } catch (Throwable ex) {
      //ignore
    }

    return new File(ClassLoaderUtil.getClassPath(), CONFIG_DIR);
  }
// ConfigUtil.java
// 返回本地缓存目录
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-----可以通过设置System的apollo.cacheDir制定缓存目录
    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-----配置文件设置apollo.cacheDir制定缓存目录
      cacheRoot = Foundation.server().getProperty("apollo.cacheDir", null);
    }

    return cacheRoot;
}

// 判断是否是windows操作系统
public boolean isOSWindows() {
    String osName = System.getProperty("os.name");
    if (Strings.isNullOrEmpty(osName)) {
      return false;
    }
    return osName.startsWith("Windows");
}

结论

  • 1)可以通过设置System(大多数是与程序有关)的apollo.cacheDir制定缓存目录
System.setProperty("apollo.cacheDir", "C:\\ydfind\\data");

结果

  • 2)配置文件C:\opt\settings\server.properties设置apollo.cacheDir制定缓存目录
apollo.cacheDir=C:\\ydfind\\data1

打断点可以看到目录正确设置了

3)getEnv系统相关变量,同理,这里不再尝试了。
4)文件拼接规则:设定目录\appid\config-cache\appid+cluster+namespace.properties

相关文章