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

时间:2023-11-23 15:28:20

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

1. 修改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"> <context:component-scan base-package="org.springinaction.weather.config" /> <!-- 使用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>
</beans>

2. 修改RedisConfig.java

实现 IDisconfUpdate 接口。此类必须是JavaBean,Spring托管的,且 “scope” 都必须是singleton的。

添加 @DisconfUpdateService 注解,classes 值加上 RedisConfig.class ,表示当 RedisConfig.class 这个配置文件更新时,此回调类将会被调用。或者,使用 confFileKeys 也可以。

 package org.springinaction.weather.config;

 import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component; import com.baidu.disconf.client.common.annotations.DisconfFile;
import com.baidu.disconf.client.common.annotations.DisconfFileItem;
import com.baidu.disconf.client.common.annotations.DisconfUpdateService;
import com.baidu.disconf.client.common.update.IDisconfUpdate; @Component("redisConfig")
@Scope("singleton")
@DisconfFile(filename = "redis.properties")
@DisconfUpdateService(classes = { RedisConfig.class })
public class RedisConfig implements IDisconfUpdate { private String host; private String port; @DisconfFileItem(name = "redis.host", associateField = "host")
public String getHost() {
return host;
} @DisconfFileItem(name = "redis.port", associateField = "port")
public String getPort() {
return port;
} @Override
public void reload() throws Exception { }
}

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