Archaius是什么?
Archaius是Netflix公司开源项目之一,基于java的配置管理类库,主要用于多配置存储的动态获取。主要功能是对apache common configuration类库的扩展。在云平台开发中可以将其用作分布式配置管理依赖构件。同时,它有如下一些特性:
动态类型化属性
高效和线程安全的配置操作
配置改变时的回调机制
轮询框架
JMX,通过Jconsole检查和调用操作属性
组合配置
在pom.xml引入archaius-core依赖:
<dependency> <groupId>com.netflix.archaius</groupId> <artifactId>archaius-core</artifactId> <version>0.6.0</version> </dependency>
可以使用下面的API在程序中得到你需要的属性
// create a property whose value is type long and use 1000 as the default
// if the property is not defined
DynamicLongProperty timeToWait =
DynamicPropertyFactory.getInstance().getLongProperty("lock.waitTime", 1000);
// ...
ReentrantLock lock = ...;
// ...
lock.tryLock(timeToWait.get(), TimeUnit.MILLISECONDS); // timeToWait.get() returns up-to-date value of the property
- 默认的:Archaius会每一分钟去重新加载下属性配置
注意:配置多属性文件时的属性覆盖,最后读到的属性会覆盖前面相同的属性
列出我们可以修改的一些系统属性
Operation | HTTP action | Notes |
archaius.configurationSource.defaultFileName | 指定Archaius默认加载的配置源属性文件名,默认:classpath:config.properties | config.properties |
archaius.fixedDelayPollingScheduler.initialDelayMills | 延迟加载,默认30秒 | 30000 |
archaius.fixedDelayPollingScheduler.delayMills | 两次属性读取时间间隔,默认1分钟 | 60000 |
高级使用:自定义configuration source和polling scheduler,即自己设计动态属性配置方案。
示例代码
在src/main/resources目录下新建config.properties配置文件,配置文件内容如下所示:
lock.waitTime=5000
Java代码:
package org.archaius.sample; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.netflix.config.DynamicLongProperty; import com.netflix.config.DynamicPropertyFactory; @Controller @SpringBootApplication public class SpringBootSampleArchaiusApplication { private static final Logger logger = LoggerFactory.getLogger(SpringBootSampleArchaiusApplication.class); @RequestMapping("/") @ResponseBody String home() { DynamicLongProperty dynamicLongProperty = DynamicPropertyFactory.getInstance().getLongProperty("lock.waitTime", 1000); logger.info(dynamicLongProperty.getName() + ":" + dynamicLongProperty.getValue()); logger.info("get:" + dynamicLongProperty.get()); return "Hello World!"; } public static void main(String[] args) { SpringApplication.run(SpringBootSampleArchaiusApplication.class, args); } }源码下载:https://gitee.com/zhmal/spring-boot-samples/tree/master/spring-boot-sample-archaius