上一篇讲解了基于xml的自动reload的分布式配置文件管理,这一篇讲解基于注解的自动reload的方式(基于disconf实践二)。
1. 修改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 <context:component-scan base-package="org.springinaction.weather.config" />
10
11 <!-- 使用disconf必须添加以下配置 -->
12 <bean id="disconfMgrBean" class="com.baidu.disconf.client.DisconfMgrBean"
13 destroy-method="destroy">
14 <property name="scanPackage" value="org.springinaction.weather.config" />
15 </bean>
16 <bean id="disconfMgrBean2" class="com.baidu.disconf.client.DisconfMgrBeanSecond"
17 init-method="init" destroy-method="destroy">
18 </bean>
19 </beans>
2. 修改RedisConfig.java
实现 IDisconfUpdate 接口。此类必须是JavaBean,Spring托管的,且 “scope” 都必须是singleton的。
添加 @DisconfUpdateService 注解,classes 值加上 RedisConfig.class ,表示当 RedisConfig.class 这个配置文件更新时,此回调类将会被调用。或者,使用 confFileKeys 也可以。
1 package org.springinaction.weather.config;
2
3 import org.springframework.context.annotation.Scope;
4 import org.springframework.stereotype.Component;
5
6 import com.baidu.disconf.client.common.annotations.DisconfFile;
7 import com.baidu.disconf.client.common.annotations.DisconfFileItem;
8 import com.baidu.disconf.client.common.annotations.DisconfUpdateService;
9 import com.baidu.disconf.client.common.update.IDisconfUpdate;
10
11 @Component("redisConfig")
12 @Scope("singleton")
13 @DisconfFile(filename = "redis.properties")
14 @DisconfUpdateService(classes = { RedisConfig.class })
15 public class RedisConfig implements IDisconfUpdate {
16
17 private String host;
18
19 private String port;
20
21 @DisconfFileItem(name = "redis.host", associateField = "host")
22 public String getHost() {
23 return host;
24 }
25
26 @DisconfFileItem(name = "redis.port", associateField = "port")
27 public String getPort() {
28 return port;
29 }
30
31 @Override
32 public void reload() throws Exception {
33
34 }
35 }
修改之后,在管理端修改redis.properties的配置信息时,应用会自动reload并修改相应的参数。