上一篇介绍了基于xml的非自动reload的分布式配置文件管理,这一篇介绍自动reload的方式(基于disconf实践二)。
1. 修改RedisConfig.java
package org.springinaction.weather.config; public class RedisConfig { private String host; private String port; public String getHost() {
return host;
} public String getPort() {
return port;
} public void setHost(String host) {
this.host = host;
} public void setPort(String port) {
this.port = port;
} }
2. 新增回调
package org.springinaction.weather.config.callback; import org.springframework.stereotype.Component; import com.baidu.disconf.client.common.annotations.DisconfUpdateService;
import com.baidu.disconf.client.common.update.IDisconfUpdate; @Component
@DisconfUpdateService(confFileKeys = { "redis.properties" })
public class RedisConfigCallback implements IDisconfUpdate { @Override
public void reload() throws Exception {
} }
3. 修改spring配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd"> <!-- 使用disconf必须添加以下配置 -->
<bean id="disconfMgrBean" class="com.baidu.disconf.client.DisconfMgrBean"
destroy-method="destroy">
<property name="scanPackage" value="org.springinaction.weather.config" />
</bean>
<bean id="disconfMgrBean2" class="com.baidu.disconf.client.DisconfMgrBeanSecond"
init-method="init" destroy-method="destroy">
</bean> <!-- 使用托管方式的disconf配置(无代码侵入, 配置更改会自动reload) -->
<bean id="configproperties_reloadable_disconf"
class="com.baidu.disconf.client.addons.properties.ReloadablePropertiesFactoryBean">
<property name="locations">
<list>
<value>redis.properties</value>
</list>
</property>
</bean> <bean id="propertyConfigurer"
class="com.baidu.disconf.client.addons.properties.ReloadingPropertyPlaceholderConfigurer">
<property name="ignoreResourceNotFound" value="true" />
<property name="ignoreUnresolvablePlaceholders" value="true" />
<property name="propertiesArray">
<list>
<ref bean="configproperties_reloadable_disconf" />
</list>
</property>
</bean> <bean id="redisConfig" class="org.springinaction.weather.config.RedisConfig">
<property name="host" value="${redis.host}" />
<property name="port" value="${redis.port}" />
</bean>
</beans>
修改之后,在管理端修改redis.properties的配置信息时,应用会自动reload并修改相应的参数。