woshikid / blog

Apache License 2.0
8 stars 1 forks source link

Archaius学习笔记 #181

Open woshikid opened 2 years ago

woshikid commented 2 years ago

POM

<!-- 需要降级Spring Cloud -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-archaius</artifactId>
    <version>2.2.10.RELEASE</version>
</dependency>

<!-- 对应Spring Boot为2.3.12.RELEASE -->
<spring-cloud.version>Hoxton.SR12</spring-cloud.version>

获取动态属性

// 注意:动态属性名不能与Spring属性相同,否则只能获取到不变的Spring属性
// ConfigurationManager
String value = ConfigurationManager.getConfigInstance().getString("my.prop", "default");
// DynamicPropertyFactory
DynamicStringProperty myprop = DynamicPropertyFactory.getInstance().getStringProperty("my.prop", "default");
String value = myprop.get();

监听属性变化

myprop.addCallback(() -> System.out.println("my.prop changed"));

默认动态配置文件

classpath:config.properties

添加动态配置文件(越靠后的优先级越高)

-Darchaius.configurationSource.additionalUrls="classpath:other/extra.properties,file:///path/to/other-extra.properties,http://localhost:8000/remote-extra.properties"

动态加载任务

# 程序启动时会立即加载一次,以下配置仅针对后续定时任务
-Darchaius.fixedDelayPollingScheduler.initialDelayMills=30000 # 初始任务延迟,默认为30秒
-Darchaius.fixedDelayPollingScheduler.delayMills=60000 # 定时任务间隔,默认为60秒

添加动态配置数据源(仅限一个) 优先级大于archaius.configurationSource.additionalUrls

@Bean
public DynamicConfiguration addArchaiusConfiguration() {
    // 文件
    PolledConfigurationSource source = new URLConfigurationSource("classpath:other/extra.properties");
    // 数据库
    //PolledConfigurationSource source = new JDBCConfigurationSource(dataSource, "select prop_key, prop_value from properties", "prop_key", "prop_value");
    return new DynamicConfiguration(source, new FixedDelayPollingScheduler());
    //return new DynamicConfiguration(source, new FixedDelayPollingScheduler(30000, 60000, false));
}

// ConfigurationManager
ConfigurationManager.install(new DynamicConfiguration(source, new FixedDelayPollingScheduler()));
// DynamicPropertyFactory
DynamicPropertyFactory.initWithConfigurationSource(new DynamicConfiguration(source, new FixedDelayPollingScheduler()));

启用JMX

# 包含所有动态配置
-Darchaius.dynamicPropertyFactory.registerConfigWithJMX=true

// 仅包含指定数据源的配置
ConfigJMXManager.registerConfigMbean(dynamicConfiguration);