Java配置分离之Spring远程配置

访问我的博客

前言

集群应用的配置文件如果写在项目的 resources 目录下面,当遇到需要修改某一个配置值时,需要将集群的所有应用的配置信息进行修改,并且将机密的配置信息比如数据库账号密码如果不进行加密配置在项目中很危险,一旦发生代码泄露问题,后果很严重。

为了避免上述情况发生,将配置信息存储到数据库中,比如数据库连接、用户名、以及密码,通过 Config 项目的一个接口提供获取配置信息。Config 项目只用于读取配置信息。

远程配置

一)新建类 RemoteProperties


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
public class RemoteProperties implements InitializingBean, FactoryBean<Properties> {

    private String url = null;

    private Properties properties = new Properties();


    @Override
    public Properties getObject() throws Exception {
        return properties;
    }

    @Override
    public Class<?> getObjectType() {
        return properties.getClass();
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        loadProperty();
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    private void loadProperty() {
        if (StringUtil.strIsNull(url)) return;
        String content = HttpClientUtil.urlGet(url);

        JSONObject object = JSONObject.parseObject(content);
        JSONArray data = object.getJSONArray("datasource");
        for (Object obj : data) {
            JSONObject jsonObject = (JSONObject) obj;
            String key = obj.getString("key");
            String value = obj.getString("value");
            properties.put(key, value);
        }
    }
}

此类用于发送请求获取配置信息,请求返回格式为 JSON 的配置信息, 如:

{
    "datasource":[
        {
            "value":"com.mysql.jdbc.Driver",
            "key":"jdbc.driver"
        },
        {
            "value":"jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8",
            "key":"jdbc.url"
        },
        {
            "value":"root",
            "key":"jdbc.username"
        },
        {
            "value":"root",
            "key":"jdbc.password"
        }
    ]
}

二)编写 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"
        xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
        xmlns:tx="http://www.springframework.org/schema/tx"
        xmlns:aop="http://www.springframework.org/schema/aop" xmlns:p="http://www.springframework.org/schema/p"
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
            http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

    <bean id="propertyConfigurerUserServer"
          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="properties">
            <bean id="remoteProperties" class="com.craft.partner.server.util.RemoteProperties"    
            p:url="http://api.xxx.com/config"/>
            <!--远程配置提供接口-->
        </property>
        
        <!--还可以加载本地的properties文件-->
        <property name="locations">
            <list>
                <value>classpath:configure.properties</value>
            </list>
        </property>
    </bean>

    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"
          p:driverClass="${jdbc.driver}" 
          p:jdbcUrl="${jdbc.url}"
          p:user="${jdbc.username}"
          p:password="${jdbc.password}">
        <property name="initialPoolSize" value="10" />
        <property name="minPoolSize" value="10" />
        <property name="maxPoolSize" value="50" />
        <property name="maxStatements" value="0" />
        <property name="maxIdleTime" value="600" />
        <property name="idleConnectionTestPeriod" value="300" />
        <property name="acquireIncrement" value="5" />
        <property name="autoCommitOnClose" value="true" />
        <property name="checkoutTimeout" value="2000" />
    </bean>

    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="save*" propagation="REQUIRED" />
            <tx:method name="update*" propagation="REQUIRED" />
            <tx:method name="delete*" propagation="REQUIRED" />
            <tx:method name="find*" read-only="true" />
            <tx:method name="*" propagation="REQUIRED" read-only="true"/><!--其他不符合规范的方法只允许读操作-->
        </tx:attributes>
    </tx:advice>

    <aop:config expose-proxy="false">
        <aop:pointcut id="serviceMethod" expression="execution(* com.craft.partner.server.service.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethod"/>
    </aop:config>
</beans>

注意: 通过 p:url="地址" 的方式,调用 RemoteProperties 的方法,发送请求获取配置信息,通过 Spring 进行注入。
注入后,可以通过 p:属性 的方式获取配置。

参考

  • http://www.cnblogs.com/yjmyzz/p/how-to-load-remote-config-in-spring.html

猜你喜欢

转载自www.cnblogs.com/vcmq/p/9484351.html
今日推荐