disconf实践(三)基于XML的分布式配置文件管理,自动reload

时间:2022-06-21 20:37:58

上一篇介绍了基于xml的非自动reload的分布式配置文件管理,这一篇介绍自动reload的方式(基于disconf实践二)。

1. 修改RedisConfig.java

 1 package org.springinaction.weather.config;
2
3 public class RedisConfig {
4
5 private String host;
6
7 private String port;
8
9 public String getHost() {
10 return host;
11 }
12
13 public String getPort() {
14 return port;
15 }
16
17 public void setHost(String host) {
18 this.host = host;
19 }
20
21 public void setPort(String port) {
22 this.port = port;
23 }
24
25 }

2. 新增回调

 1 package org.springinaction.weather.config.callback;
2
3 import org.springframework.stereotype.Component;
4
5 import com.baidu.disconf.client.common.annotations.DisconfUpdateService;
6 import com.baidu.disconf.client.common.update.IDisconfUpdate;
7
8 @Component
9 @DisconfUpdateService(confFileKeys = { "redis.properties" })
10 public class RedisConfigCallback implements IDisconfUpdate {
11
12 @Override
13 public void reload() throws Exception {
14 }
15
16 }

3. 修改spring配置文件

 1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
4 xsi:schemaLocation="http://www.springframework.org/schema/beans
5 http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
6 http://www.springframework.org/schema/context
7 http://www.springframework.org/schema/context/spring-context-4.3.xsd">
8
9 <!-- 使用disconf必须添加以下配置 -->
10 <bean id="disconfMgrBean" class="com.baidu.disconf.client.DisconfMgrBean"
11 destroy-method="destroy">
12 <property name="scanPackage" value="org.springinaction.weather.config" />
13 </bean>
14 <bean id="disconfMgrBean2" class="com.baidu.disconf.client.DisconfMgrBeanSecond"
15 init-method="init" destroy-method="destroy">
16 </bean>
17
18 <!-- 使用托管方式的disconf配置(无代码侵入, 配置更改会自动reload) -->
19 <bean id="configproperties_reloadable_disconf"
20 class="com.baidu.disconf.client.addons.properties.ReloadablePropertiesFactoryBean">
21 <property name="locations">
22 <list>
23 <value>redis.properties</value>
24 </list>
25 </property>
26 </bean>
27
28 <bean id="propertyConfigurer"
29 class="com.baidu.disconf.client.addons.properties.ReloadingPropertyPlaceholderConfigurer">
30 <property name="ignoreResourceNotFound" value="true" />
31 <property name="ignoreUnresolvablePlaceholders" value="true" />
32 <property name="propertiesArray">
33 <list>
34 <ref bean="configproperties_reloadable_disconf" />
35 </list>
36 </property>
37 </bean>
38
39 <bean id="redisConfig" class="org.springinaction.weather.config.RedisConfig">
40 <property name="host" value="${redis.host}" />
41 <property name="port" value="${redis.port}" />
42 </bean>
43 </beans>

修改之后,在管理端修改redis.properties的配置信息时,应用会自动reload并修改相应的参数。