1.apollo 安装
apolloconfig/apollo-build-scripts: Apollo Quick Start Build Scripts (github.com)
window 安装借助:git 进行
2.spring boot 接入
<dependency> <groupId>com.ctrip.framework.apollo</groupId> <artifactId>apollo-client</artifactId> <version>1.1.0</version> </dependency>
application.properties
#appId 同来区别不同的配置 app.id=SampleApp #apollo服务器地址 apollo.meta=http://localhost:8080
代码
package com.example.demo.config; import com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration @EnableApolloConfig public class AppConfig { @Bean public TestJavaConfigBean javaConfigBean() { return new TestJavaConfigBean(); } }
package com.example.demo.config; import org.springframework.beans.factory.annotation.Value; public class TestJavaConfigBean { @Value("${timeout:100}") private int timeout; private int batch; @Value("${batch:200}") public void setBatch(int batch) { this.batch = batch; } public int getTimeout() { return timeout; } public int getBatch() { return batch; } }
使用
package com.example.demo.schedule; import com.example.demo.config.TestJavaConfigBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component @EnableScheduling public class ScheduledTest { @Autowired private TestJavaConfigBean testJavaConfigBean; @Scheduled(cron = "0/5 * * * * ?") public void executeFileDownLoadTask() { // 间隔2分钟,执行任务 int timeout = testJavaConfigBean.getTimeout(); System.out.println("定时任务1:" + timeout); } }
结果:
自动监听:
@Configuration public class LoggerConfig { private static final Logger logger = LoggerFactory.getLogger(LoggerConfig.class); private static final String LOGGER_TAG = "logging.level."; @Autowired private LoggingSystem loggingSystem; @ApolloConfig private Config config; @ApolloConfigChangeListener private void configChangeListter(ConfigChangeEvent changeEvent) { refreshLoggingLevels(); } @PostConstruct private void refreshLoggingLevels() { Set<String> keyNames = config.getPropertyNames(); for (String key : keyNames) { if (StringUtils.containsIgnoreCase(key, LOGGER_TAG)) { String strLevel = config.getProperty(key, "info"); LogLevel level = LogLevel.valueOf(strLevel.toUpperCase()); loggingSystem.setLogLevel(key.replace(LOGGER_TAG, ""), level); logger.info("{}:{}", key, strLevel); } } } }