import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigChangeListener;
import com.ctrip.framework.apollo.ConfigService;
import com.ctrip.framework.apollo.model.ConfigChange;
import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.core.io.FileSystemResource;
import java.util.Properties;
import java.util.Set;
@SpringBootApplication
@Slf4j
public class LitchiDaqApplication {
private static Properties PROPERTIES = new Properties();
public static void main(String[] args) {
// SpringApplication.run(LitchiDaqApplication.class, args);
try {
String filePath = System.getProperty("user.dir") + "/config" + "/application-daq.yml";
//此处获取启动参数中的config.id来判断从哪里读取config文件
String configId = System.getProperty("config.id");
if (configId != null) {
//从Apollo配置中心获取配置
Config config = ConfigService.getAppConfig();
//监听apollo配置修改
config.addChangeListener(new ConfigChangeListener() {
@Override
public void onChange(ConfigChangeEvent changeEvent) {
log.info("发生改变的工作区: {}", changeEvent.getNamespace());
for (String key : changeEvent.changedKeys()) {
ConfigChange change = changeEvent.getChange(key);
log.info(String.format("检测到改变 - key: %s, oldValue: %s, newValue: %s, changeType: %s",
change.getPropertyName(), change.getOldValue(), change.getNewValue(), change.getChangeType()));
}
}
});
Set<String> keys = config.getPropertyNames();
for (String key : keys) {
PROPERTIES.setProperty(key, config.getProperty(key, null));
}
} else {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(new FileSystemResource(filePath));
PROPERTIES = factory.getObject();
}
} catch (Exception e) {
log.error("项目初始化配置错误:", e);
}
new SpringApplicationBuilder(LitchiDaqApplication.class).properties(PROPERTIES).run(args);
}
}
|