社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
1.Apollo 是什么?Apollo(阿波罗)是携程框架部门研发的分布式配置中心。服务端基于Spring Boot和Spring Cloud开发。
2.为什么要使用Apollo?
注:本文主要介绍SpringBoot 整合 Apollo 实现动态配置
<dependency>
<groupId>com.ctrip.framework.apollo</groupId>
<artifactId>apollo-client</artifactId>
<version>1.3.0</version>
</dependency>
# apollo集成
# apollo 配置应用的 appid
app.id=springboot-apollo-demo1
# apollo meta-server地址,一般同config-server地址
apollo.meta=http://192.168.0.153:8080
#启用apollo配置开关
apollo.bootstrap.enabled=true
apollo.bootstrap.eagerLoad.enabled=true
# apollo 使用配置的命名空间,多个以逗号分隔
apollo.bootstrap.namespaces = application
配置说明:
图示说明:
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class})
public class SpringbootApolloApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootApolloApplication.class, args);
}
}
基于@Value注解配置
@Component
public class ValueStyleProperty {
@Value("${apollo.value.demoKey1}")
private String demoKey1;
@Value("${apollo.value.demoKey2}")
private String demoKey2;
//省略 get/set 方法
}
/**
* value注解方式,获取属性
*
* @author mengqiang
*/
@RestController
@RequestMapping("/value-style")
public class ValuePropertyController {
@Autowired
private ValueStyleProperty keyProperty;
@Value("${server.port}")
private String port;
@Value("${apollo.bootstrap.namespaces:'application'}")
private String namespaces;
@GetMapping("/get")
public Map<String, Object> getProperty() {
Map<String, Object> map = new LinkedHashMap<>();
map.put("port", port);
map.put("namespaces", namespaces);
map.put("demoKey1", keyProperty.getDemoKey1());
map.put("demoKey2", keyProperty.getDemoKey2());
return map;
}
}
配置说明:
项目配置主页截图
注:不能批量操作
注:配置只有发布后才会生效
点击发布按钮
注意事项:
点击同步配置
选择需要同步的配置,以及目标环境
点击同步
目标环境查看
发布后控制台变化
测试输出值变化
示例配置类
/**
* 公共开关,key值 属性配置
*
* @author mengqiang
*/
@Component
@ConfigurationProperties(prefix = "apollo.first.config")
public class ConfigFirstProperty {
/**
* 测试数字
*/
private Integer oneNumber;
/**
* 测试字符串
*/
private String oneStr;
/**
* 启用标记
*/
private Boolean oneEnableFlag;
/**
* 税率 默认 0.03
*/
private BigDecimal oneTaxRate = new BigDecimal("0.03");
//省略 get/set 方法
}
解决方案
添加监听配置
import com.ctrip.framework.apollo.model.ConfigChange;
import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.cloud.context.environment.EnvironmentChangeEvent;
/**
* Apollo 配置监听
*/
@Configuration
public class ApolloConfigListener implements ApplicationContextAware {
/**
* 日志
*/
private static final Logger LOGGER = LoggerFactory.getLogger(ApolloConfigListener.class);
private ApplicationContext applicationContext;
/**
* 配置监听
* ApolloConfigChangeListener > value 属性默认 命名空间 "application"
*
* 示例: @ApolloConfigChangeListener(value = {"application", "test_space"})
*/
@ApolloConfigChangeListener
private void onChange(ConfigChangeEvent changeEvent) {
LOGGER.info("【Apollo-config-change】start");
for (String key : changeEvent.changedKeys()) {
ConfigChange change = changeEvent.getChange(key);
LOGGER.info("key={} , propertyName={} , oldValue={} , newValue={} ", key, change.getPropertyName(), change.getOldValue(), change.getNewValue());
}
// 更新相应的bean的属性值,主要是存在@ConfigurationProperties注解的bean
this.applicationContext.publishEvent(new EnvironmentChangeEvent(changeEvent.changedKeys()));
LOGGER.info("【Apollo-config-change】end");
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
示例配置
logging.level.com.example=info
解决方案-日志监听器
import com.ctrip.framework.apollo.model.ConfigChange;
import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.logging.LogLevel;
import org.springframework.boot.logging.LoggingSystem;
import org.springframework.context.annotation.Configuration;
import javax.annotation.Resource;
/**
* Apollo 日志-配置监听
*/
@Configuration
public class LoggerConfigListener {
private static final Logger LOGGER = LoggerFactory.getLogger(LoggerConfigListener.class);
private static final String LOGGER_TAG = "logging.level.";
@Resource
private LoggingSystem loggingSystem;
/**
* 监听 日志配置的变化
*/
@ApolloConfigChangeListener(interestedKeyPrefixes = LOGGER_TAG)
private void onChangeLogger(ConfigChangeEvent changeEvent) {
LOGGER.info("【Apollo-logger-config-change】>> start");
refreshLoggingLevel(changeEvent);
LOGGER.info("【Apollo-logger-config-change】>> end");
}
/**
* 刷新日志级别
*/
private void refreshLoggingLevel(ConfigChangeEvent changeEvent) {
if (null == loggingSystem) {
return;
}
for (String key : changeEvent.changedKeys()) {
ConfigChange change = changeEvent.getChange(key);
if (!StringUtils.containsIgnoreCase(key, LOGGER_TAG)) {
continue;
}
LOGGER.info("【Apollo-logger-config-change】>> key={} , propertyName={} , oldValue={} , newValue={} ",
key, change.getPropertyName(), change.getOldValue(), change.getNewValue());
String newLevel = change.getNewValue();
LogLevel level = LogLevel.valueOf(newLevel.toUpperCase());
loggingSystem.setLogLevel(key.replace(LOGGER_TAG, ""), level);
LOGGER.info("【Apollo-logger-config-change】>> {} -> {}", key, newLevel);
}
}
}
注:由于 4.1与4.2监听有重合,所以最好放在一起处理
import com.ctrip.framework.apollo.model.ConfigChange;
import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.boot.logging.LogLevel;
import org.springframework.boot.logging.LoggingSystem;
import org.springframework.cloud.context.environment.EnvironmentChangeEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;
import javax.annotation.Resource;
/**
* Apollo 配置监听
*/
@Configuration
public class ApolloConfigListener implements ApplicationContextAware {
/**
* 日志
*/
private static final Logger LOGGER = LoggerFactory.getLogger(ApolloConfigListener.class);
/**
* 日志配置常量
*/
private static final String LOGGER_TAG = "logging.level.";
@Resource
private LoggingSystem loggingSystem;
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
/**
* 配置监听
* ApolloConfigChangeListener > value 属性默认 命名空间 "application"
*/
@ApolloConfigChangeListener
private void onChangeConfig(ConfigChangeEvent changeEvent) {
LOGGER.info("【Apollo-config-change】>> start");
for (String key : changeEvent.changedKeys()) {
ConfigChange change = changeEvent.getChange(key);
LOGGER.info("【Apollo-config-change】>> key={} , propertyName={} , oldValue={} , newValue={} ",
key, change.getPropertyName(), change.getOldValue(), change.getNewValue());
//是否为日志配置
if (StringUtils.containsIgnoreCase(key, LOGGER_TAG)) {
//日志配置刷新
changeLoggingLevel(key, change);
continue;
}
// 更新相应的bean的属性值,主要是存在@ConfigurationProperties注解的bean
this.applicationContext.publishEvent(new EnvironmentChangeEvent(changeEvent.changedKeys()));
}
LOGGER.info("【Apollo-config-change】>> end");
}
/**
* 刷新日志级别
*/
private void changeLoggingLevel(String key, ConfigChange change) {
if (null == loggingSystem) {
return;
}
String newLevel = change.getNewValue();
LogLevel level = LogLevel.valueOf(newLevel.toUpperCase());
loggingSystem.setLogLevel(key.replace(LOGGER_TAG, ""), level);
LOGGER.info("【Apollo-logger-config-change】>> {} -> {}", key, newLevel);
}
}
4.4.1配置文件与配置中心同时存在配置,启用的是那一份
apollo 配置开关开启情况下,配置中心配置会覆盖本地配置
注:配置开关 apollo.bootstrap.enabled=true
4.4.2 配置中心挂掉会影响已发布的项目吗?
项目启动后配置会存在缓存中,配置中心挂掉,已发布的项目不影响
4.4.3 是否支持更新端口配置
支持更新端口配置,但是必需要重启生效,同时也需要考虑服务器的端口占用问题。
官方源码地址:https://github.com/ctripcorp/apollo
官方演示环境(Demo):
快速搭建本地测试环境
https://github.com/ctripcorp/apollo/wiki/Quick-Start
分布式部署指南(生产环境建议使用)https://github.com/ctripcorp/apollo/wiki/%E5%88%86%E5%B8%83%E5%BC%8F%E9%83%A8%E7%BD%B2%E6%8C%87%E5%8D%97
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!