---
title: "分布式配置文件管理工具disconf部署以及运用"
author: "spjich"
date: "2016-04-27T17:59:12Z"
tags: []
categories: ["企业架构"]
slug: "disconf"
draft: false
lastmod: "2016-04-27T18:03:09Z"
id: 2294369
url: "https://spjich.iteye.com/blog/2294369"
---

disconf之前有搭建过一次但是没有成功，比较纠结它的基于nginx实现动静分离的思想，其实明明可以少一个组件的依赖和配置，或许开发者有其自己的考虑吧。

这次终于搭建完毕并且跑通，下面写几个碰到但是官方文档中没给出的坎。

 

 

 

 

# 搭建项目

 --就是一个disconf-web

### 安装依赖软件

- 安装Mysql（Ver 14.12 Distrib 5.0.45, for unknown-linux-gnu (x86\_64) using EditLine wrapper）
- 安装Tomcat（apache-tomcat-7.0.50）
- 安装Nginx（nginx/1.5.3）
- 安装 zookeeeper （zookeeper-3.3.0）
- 安装 Redis （2.4.5）

### [](https://github.com/knightliao/disconf/tree/master/disconf-web#%E5%87%86%E5%A4%87%E9%85%8D%E7%BD%AE)准备配置

将你的配置文件放到此地址目录下（以下地址可自行设定）：

```
home/work/dsp/disconf-rd/online-resources
```

配置文件包括：

```
- jdbc-mysql.properties (数据库配置)
- redis-config.properties (Redis配置)
- zoo.properties (Zookeeper配置)
- application.properties (应用配置）
```

注意，记得执行将application-demo.properties复制成application.properties：

```
cp application-demo.properties application.properties 
```

设置War包将要被部署的地址（以下地址可自行设定）：

```
/home/work/dsp/disconf-rd/war
```

### [](https://github.com/knightliao/disconf/tree/master/disconf-web#%E6%9E%84%E5%BB%BA)构建

```
ONLINE_CONFIG_PATH=/home/work/dsp/disconf-rd/online-resources
WAR_ROOT_PATH=/home/work/dsp/disconf-rd/war
export ONLINE_CONFIG_PATH
export WAR_ROOT_PATH
cd disconf-web
sh deploy/deploy.sh
```

这样会在 /home/work/dsp/disconf-rd/war 生成以下结果：

```
-disconf-web.war  
-html  
-META-INF  
-WEB-INF
```

### [](https://github.com/knightliao/disconf/tree/master/disconf-web#%E4%B8%8A%E7%BA%BF%E5%89%8D%E7%9A%84%E5%88%9D%E5%A7%8B%E5%8C%96%E5%B7%A5%E4%BD%9C)上线前的初始化工作

初始化数据库：

可以参考 sql/readme.md 来进行数据库的初始化。

里面默认有6个用户

如果想自己设置初始化的用户名信息，可以参考代码来自己生成用户：

```
src/main/java/com/baidu/disconf/web/tools/UserCreateTools.java
```

### [](https://github.com/knightliao/disconf/tree/master/disconf-web#%E9%83%A8%E7%BD%B2war)部署War

修改server.xml文件，在Host结点下设定Context：

```
<Context path="" docBase="/home/work/dsp/disconf-rd/war"></Context>
```

并设置端口为 8015

启动Tomcat，即可。

### [](https://github.com/knightliao/disconf/tree/master/disconf-web#%E9%83%A8%E7%BD%B2-%E5%89%8D%E7%AB%AF)部署 前端

修改 nginx.conf

```
upstream disconf {
    server 127.0.0.1:8015;
}

server {

    listen   8081;
    server_name localhost;
    access_log /home/work/var/logs/disconf/access.log;
    error_log /home/work/var/logs/disconf/error.log;

    location / {
        root /home/work/dsp/disconf-rd/war/html;
        if ($query_string) {
            expires max;
        }
    }

    location ~ ^/(api|export) {
        proxy_pass_header Server;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Scheme $scheme;
        proxy_pass http://disconf;
    }
}
```

特别指出在打包项目时候请检查python库版本3.\*版本会报错，请用2.\*打包

第二点，在打出来的war包修改诸如zookeeper的配置时，必须重新打包，单纯修改war目录下的文件是无效的

 

 

 

 

 

 

 

 

 

 

 

 

 

# 使用

用户名密码 admin/admin

创建app，上传配置

![](http://dl2.iteye.com/upload/attachment/0117/0186/e5bd6fa7-642b-3dca-bca3-39a140f869c4.png)  
1.添加disconf.properties配置文件

  disconf.user\_define\_download\_dir=./                                 此处意思就是将zookeeper中的配置拉到本地的classpath下，若配置成其他目录，似乎会报错

```
disconf.enable.remote.conf=true
disconf.conf_server_host=172.171.51.151:8082
disconf.version=1.0.0.0
disconf.app=17wifiServer
disconf.env=local
disconf.ignore=
disconf.conf_server_url_retry_times=1
disconf.conf_server_url_retry_sleep_seconds=1
disconf.user_define_download_dir=./
disconf.enable_local_download_dir_in_class_path=true
```

 

2.添加disconf.xml，并且指定给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:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
    <aop:aspectj-autoproxy proxy-target-class="true"/>
    <!-- 使用disconf必须添加以下配置 -->
    <bean id="disconfMgrBean" class="com.baidu.disconf.client.DisconfMgrBean"
          destroy-method="destroy">
        <property name="scanPackage" value="com.fnic.wifi.server"/>
    </bean>
    <bean id="disconfMgrBean2" class="com.baidu.disconf.client.DisconfMgrBeanSecond"
          init-method="init" destroy-method="destroy">
    </bean>
    <!--################################################################ -->
    <!-- 使用托管方式的disconf配置(无代码侵入, 配置更改会自动reload)-->
    <bean id="configproperties_disconf"
          class="com.baidu.disconf.client.addons.properties.ReloadablePropertiesFactoryBean">
        <property name="locations">
            <list>
                                <value>classpath:jdbc.properties</value>
				<value>classpath: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_disconf"/>
            </list>
        </property>
    </bean>  
</beans>
```

 配置上半段是必须配置，下半段是将配置文件托管给spring，并且可以运用${}这样的形式配置在spring的xml中，可以参考jdbc数据源的配置

其中

```
<value>classpath:jdbc.properties</value>
<value>classpath:redis.properties</value>
要和上面
disconf.user_define_download_dir=./ 对应起来
```

 

 

 

3.注释掉spring原本的加载配置类

```
<!--    	<bean id="config"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>classpath:conf/jdbc.properties</value>
				<value>classpath:conf/redis.properties</value>
			</list>
		</property>
	</bean> -->  
```

 4.编写测试bean

```
@Component
@DisconfFile(filename = "configure.properties")
public class ConfDIs {
	private String resourceUrl;

	@DisconfFileItem(name = "resource_server_url", associateField = "resourceUrl")
	public String getResourceUrl() {
		return resourceUrl;
	}

	public void setResourceUrl(String resourceUrl) {
		this.resourceUrl = resourceUrl;
	}

}
```

 

ok启动就可以运用disconf了，其性能还有待验证，不过其原理应该是从zk中拉配置到本地内存中，同自己手动加载本地的property文件。

正常的日志如下

```
2016-04-27 17:57:27 [com.baidu.disconf.client.DisconfMgr]-[INFO] ******************************* DISCONF END FIRST SCAN *******************************
2016-04-27 17:57:28 [org.springframework.beans.GenericTypeAwarePropertyDescriptor]-[WARN] Invalid JavaBean property 'locations' being accessed! Ambiguous write methods found next to actually used [public void com.baidu.disconf.client.addons.properties.ReloadablePropertiesFactoryBean.setLocations(java.util.List)]: [public void org.springframework.core.io.support.PropertiesLoaderSupport.setLocations(org.springframework.core.io.Resource[])]
2016-04-27 17:57:28 [com.baidu.disconf.client.addons.properties.ReloadablePropertiesFactoryBean]-[INFO] Loading properties file from class path resource [jdbc.properties]
2016-04-27 17:57:28 [com.baidu.disconf.client.addons.properties.ReloadablePropertiesFactoryBean]-[INFO] Loading properties file from class path resource [redis.properties]
2016-04-27 17:57:28 [org.springframework.beans.factory.support.DefaultListableBeanFactory]-[INFO] Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@63b7e77: defining beans [wifiAspect,activityDataBuilder,apActiveManageController,adDataBuilder,apAdController,apResourceController,resourceDataBuilder,apUserController,busController,busOnlineController,clickStatistics,confDIs,couponController,apFeedBackController,apFindAroundController,indexController,splashDataBuilder,messageSendController,sendMailController,pluginController,appScoreController,versionController,wifiAuthController,startListener,busServiceImpl,activityServiceImpl,apAdServiceImpl,apFeedBackSeriveImpl,appScoreServiceImpl,apResourceServiceImpl,apUserServiceImpl,busOnlineServiceImpl,couponServiceImpl,DAServiceImpl,findAroundServiceImpl,groupServiceImpl,indexServiceImpl,messageSendServiceImpl,pluginServiceImpl,versionServiceImpl,wifiAuthServiceImpl,httpService,springHolder,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,jedisPoolConfig,jedisConnFactory,stringRedisTemplate,objRedisTemplate,redisObj,redisString,redisTemplate,redisSubscribe,messageDelegateListener,serialization,messageListener,redisContainer,dataSource,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,sqlSessionFactory,org.mybatis.spring.mapper.MapperScannerConfigurer#0,transactionManager,disconfMgrBean,disconfMgrBean2,configproperties_disconf,propertyConfigurer,disconfAspectJ,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor,activityDao,apAdDao,apFeedBackDao,appScoreDao,apResourceDao,apUserDao,busDao,busOnlineDao,couponDao,DADao,findAroundDao,groupDao,indexDao,messageSendDao,pluginDao,versionDao,wifiAuthDao]; root of factory hierarchy
2016-04-27 17:57:28 [com.fnic.wifi.server.aop.WifiAspect]-[INFO] 初始化Controller Aop
2016-04-27 17:57:30 [com.baidu.disconf.client.DisconfMgr]-[INFO] ******************************* DISCONF START SECOND SCAN *******************************
2016-04-27 17:57:30 [com.baidu.disconf.client.DisconfMgr]-[INFO] Conf File Map: 
disconf-file:	redis.properties	
	DisconfCenterFile [
	keyMaps={}
	additionalKeyMaps={redis.maxWait=3000, redis.hostName=172.171.51.154, redis.maxIdle=5, redis.port=6380, redis.maxActive=500}
	cls=null
	remoteServerUrl=/api/config/file?app=17wifiServer&env=local&type=0&key=redis.properties&version=1.0.0.0]
disconf-file:	jdbc.properties	
	DisconfCenterFile [
	keyMaps={}
	additionalKeyMaps={jdbc.url=jdbc:mysql://172.171.48.110:3306/wifimanage?characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull, jdbc.minIdle=5, jdbc.username=root, jdbc.maxWait=3000, jdbc.removeAbandoned=true, jdbc.maxActive=15, jdbc.removeAbandonedTimeout=300, jdbc.maxIdle=30, jdbc.logAbandoned=true, jdbc.driver=com.mysql.jdbc.Driver, jdbc.password=root}
	cls=null
	remoteServerUrl=/api/config/file?app=17wifiServer&env=local&type=0&key=jdbc.properties&version=1.0.0.0]
disconf-file:	configure.properties	
	DisconfCenterFile [
	keyMaps={resource_server_url=FileItemValue{value=http://172.171.51.151:8081/Resources2/, field=private java.lang.String com.fnic.wifi.server.controller.ConfDIs.resourceUrl, setMethod=null}}
	additionalKeyMaps={}
	cls=class com.fnic.wifi.server.controller.ConfDIs
	remoteServerUrl=/api/config/file?app=17wifiServer&env=local&type=0&key=configure.properties&version=1.0.0.0]

2016-04-27 17:57:30 [com.baidu.disconf.client.DisconfMgr]-[INFO] Conf Item Map: 

2016-04-27 17:57:30 [com.baidu.disconf.client.DisconfMgr]-[INFO] ******************************* DISCONF END *******************************
```