先占个坑,这篇主要记录查找更新失败的问题上, 后期有时间会详细补充ConfigServer的主要源码分析。
源码阅读目标
- 启动过程
- Restful获取配置原理过程
启动
- 通过注解引入4个class
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import({ EnvironmentRepositoryConfiguration.class, ResourceRepositoryConfiguration.class,
ConfigServerEncryptionConfiguration.class, ConfigServerMvcConfiguration.class })
public @interface EnableConfigServer {
}
- EnvironmentRepositoryConfiguration 配置 environmentRepository
Profile为native或者subversion分别配置native和svn的repository, 否则为git
-
ResourceRepositoryConfiguration:Resource仓库配置
-
ConfigServerEncryptionConfiguration: 加密bean 注册
-
ConfigServerMvcConfiguration: controller baen注册
Restful获取配置原理过程
- 对于git上配置更新,configserver是在restful请求的时候再更新的。
- Controller -> XXX(这部分调用很简单,略过) -> AbstractScmEnvironmentRepository.findOne -> JGitEnvironmentRepository.getLocations -> JGitEnvironmentRepository.refresh -> JGitEnvironmentRepository.shouldPull(判断是否需要pull) -> pull
AbstractScmEnvironmentRepository.java
@Override
public synchronized Environment findOne(String application, String profile, String label) {
NativeEnvironmentRepository delegate = new NativeEnvironmentRepository(
getEnvironment());
Locations locations = getLocations(application, profile, label);
delegate.setSearchLocations(locations.getLocations());
Environment result = delegate.findOne(application, profile, "");
result.setVersion(locations.getVersion());
result.setLabel(label);
return this.cleaner.clean(result, getWorkingDirectory().toURI().toString(),
getUri());
}
JGitEnvironmentRepository.java
@Override
public synchronized Locations getLocations(String application, String profile,
String label) {
if (label == null) {
label = this.defaultLabel;
}
Ref ref = refresh(application, label);
String version = null;
if (ref != null) {
version = ref.getObjectId().getName();
}
return new Locations(application, profile, label, version,
getSearchLocations(getWorkingDirectory(), application, profile, label));
}
private Ref refresh(String application, String label) {
initialize();
Git git = null;
try {
git = createGitClient();
git.getRepository().getConfig().setString("branch", label, "merge", label);
Ref ref = checkout(git, label);
if (shouldPull(git, ref)) {
pull(git, label, ref);
}
return ref;
}
catch (RefNotFoundException e) {
throw new NoSuchLabelException("No such label: " + label);
}
catch (GitAPIException e) {
throw new IllegalStateException("Cannot clone or checkout repository", e);
}
catch (Exception e) {
throw new IllegalStateException("Cannot load environment", e);
}
finally {
try {
if (git != null) {
git.close();
}
}
catch (Exception e) {
this.logger.warn("Could not close git repository", e);
}
}
}