79 lines
2.0 KiB
Java
79 lines
2.0 KiB
Java
|
package com.cm.common.manager;
|
||
|
|
||
|
|
||
|
import com.cm.common.dao.IEnvDao;
|
||
|
import com.cm.common.pojo.Env;
|
||
|
import com.cm.common.pojo.dtos.env.EnvDTO;
|
||
|
import org.apache.commons.lang3.StringUtils;
|
||
|
import org.slf4j.Logger;
|
||
|
import org.slf4j.LoggerFactory;
|
||
|
|
||
|
import java.util.List;
|
||
|
import java.util.regex.Matcher;
|
||
|
import java.util.regex.Pattern;
|
||
|
|
||
|
|
||
|
public class EnvManager {
|
||
|
|
||
|
private static final Logger LOG = LoggerFactory.getLogger(EnvManager.class);
|
||
|
private static EnvManager envManager = EnvManagerBuilder.envManager;
|
||
|
private static Pattern ENV_VARIABLE = Pattern.compile("%[a-zA-Z\\d\\_\\-]+%");
|
||
|
private IEnvDao envDao;
|
||
|
private Env env = new Env();
|
||
|
|
||
|
private EnvManager() {}
|
||
|
|
||
|
public static EnvManager getInstance() {
|
||
|
return envManager;
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* 刷新环境变量
|
||
|
*/
|
||
|
public void refreshEnv() {
|
||
|
env.clear();
|
||
|
List<EnvDTO> envDTOS = envDao.list();
|
||
|
envDTOS.forEach(envDTO -> {
|
||
|
env.put(envDTO.getEnvKey(), envDTO.getEnvValue());
|
||
|
});
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* 获得环境变量
|
||
|
*
|
||
|
* @return
|
||
|
*/
|
||
|
public Env getEnv() {
|
||
|
return env;
|
||
|
}
|
||
|
|
||
|
public boolean isKeyExist(String key) {
|
||
|
return env.containsKey(key);
|
||
|
}
|
||
|
|
||
|
public String getValue(String key) {
|
||
|
String value = env.get(key);
|
||
|
value = value == null ? "" : value;
|
||
|
// 替换变量
|
||
|
Matcher matcher = ENV_VARIABLE.matcher(value);
|
||
|
while (matcher.find()) {
|
||
|
String variable = matcher.group();
|
||
|
String variableValue = env.get(variable.substring(1, variable.length() - 1));
|
||
|
if (StringUtils.isBlank(variableValue)) {
|
||
|
continue;
|
||
|
}
|
||
|
value = value.replaceFirst(variable, variableValue);
|
||
|
}
|
||
|
return value;
|
||
|
}
|
||
|
|
||
|
public void setEnvDao(IEnvDao envDao) {
|
||
|
this.envDao = envDao;
|
||
|
}
|
||
|
|
||
|
private static class EnvManagerBuilder {
|
||
|
public static final EnvManager envManager = new EnvManager();
|
||
|
}
|
||
|
|
||
|
}
|