spring+hibernate配置多数据源的问题

来源:互联网 发布:淘宝q币充错了 编辑:程序博客网 时间:2024/06/05 09:54
因工作原因,需要从不同数据库中获取数据,而这些数据库又不是分布式的,不能利用分库的方式来解决问题,所以需要多个数据源。
配置多个数据源的步骤如下:
步骤一:首先我们需要编写一个获取数据源的工具类
package cn.ruida.mq.train.util;/** * 作用:获取数据源的工具类 * @author tianqiang.shao * @date 2014年7月15日 上午8:23:28 */public class DataSourceContextHolder {    //创建一个线程本地环境    private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();    /**     * 作用:设置数据源类型     * @author tianqiang.shao     * @date 2014年7月15日 上午8:26:58     * @param dataSourceType     */    public static void setDataSourceType(String dataSourceType){        contextHolder.set(dataSourceType);    }    /**     * 作用:获取数据源类型     * @author tianqiang.shao     * @date 2014年7月15日 上午8:27:50     * @return     */    public static String getDataSourceType(){        return contextHolder.get();    }    /**     * 作用:清除数据源类型     * @author tianqiang.shao     * @date 2014年7月15日 上午8:28:26     */    public static void clearDataSourceType(){        contextHolder.remove();    } }
步骤二:编写一个数据源枚举类(此步骤可以不写)
package cn.ruida.mq.train.product.datasource;/** * 作用:数据源枚举类 * @author tianqiang.shao * @date 2014年7月15日 上午8:33:22 */public enum DataSourceEnum {    HZDATASOURCE("hzDataSource","杭州数据源"),TZDATASOURCE("tzDataSource","台州数据源");    private String key;    private String value;    private DataSourceEnum(String key,String value){        this.key = key;        this.value = value;    }    public String getKey() {        return key;    }    public String getValue() {        return value;    } } 
步骤三:编写一个类:获取动态数据源
package cn.ruida.mq.train.product.datasource;import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;import cn.ruida.mq.train.util.DataSourceContextHolder;/** * 作用:获取动态的数据源 * @author tianqiang.shao * @date 2014年7月15日 上午8:30:10 */public class DynamicDataSource extends AbstractRoutingDataSource {    @Override    protected Object determineCurrentLookupKey() {        return DataSourceContextHolder.getDataSourceType();    }}
步骤四:配置application-dao.xml
1)配置数据源1
<!-- 配置一个父类数据源 -->    <bean id="dataSource_hz" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">      <!-- 基本属性 url、user、password -->        <property name="url" value="${hz.jdbc.url}" />        <property name="username" value="${hz.jdbc.username}" />        <property name="password" value="${hz.jdbc.password}" /><!-- 配置初始化大小、最小、最大 -->              <property name="initialSize" value="1" />        <property name="minIdle" value="1" />        <property name="maxActive" value="20" />        <!-- 配置获取连接等待超时的时间 -->        <property name="maxWait" value="60000" />        <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->        <property name="timeBetweenEvictionRunsMillis" value="60000" />        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->        <property name="minEvictableIdleTimeMillis" value="300000" />        <property name="validationQuery" value="SELECT 'x'" />        <property name="testWhileIdle" value="true" />        <property name="testOnBorrow" value="false" />        <property name="testOnReturn" value="false" />        <!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->        <property name="poolPreparedStatements" value="false" />        <property name="proxyFilters">            <list>                <ref bean="stat-filter" />            </list>        </property>    </bean>  
2)配置数据源2
<bean id="dataSource_tz" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">      <!-- 基本属性 url、user、password -->        <property name="url" value="${tz.jdbc.url}" />        <property name="username" value="${tz.jdbc.username}" />        <property name="password" value="${tz.jdbc.password}" />              <property name="initialSize" value="1" />        <property name="minIdle" value="1" />        <property name="maxActive" value="20" />        <!-- 配置获取连接等待超时的时间 -->        <property name="maxWait" value="60000" />        <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->        <property name="timeBetweenEvictionRunsMillis" value="60000" />        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->        <property name="minEvictableIdleTimeMillis" value="300000" />        <property name="validationQuery" value="SELECT 'x'" />        <property name="testWhileIdle" value="true" />        <property name="testOnBorrow" value="false" />        <property name="testOnReturn" value="false" />        <!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->        <property name="poolPreparedStatements" value="false" />        <property name="proxyFilters">            <list>                <ref bean="stat-filter" />            </list>        </property> </bean>  
3)配置dataSource
<!-- 编写spring 配置文件的配置多数源映射关系 -->    <bean id="dataSource" class="cn.ruida.mq.train.product.datasource.DynamicDataSource" >      <property name="targetDataSources">        <map key-type="java.lang.String">         <entry value-ref="dataSource_hz" key="hzDataSource"></entry>         <entry value-ref="dataSource_tz" key="tzDataSource"></entry>        </map>      </property>      <property name="defaultTargetDataSource"  ref="dataSource_hz"></property>   </bean>  
4)配置sessionFactory
<!-- 配置sessionFactory -->    <bean id="sessionFactory"        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">        <property name="dataSource" ref="dataSource" />        <property name="hibernateProperties">            <props>                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>                <prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext                </prop>            </props>        </property>        <property name="resourceLoader">            <bean                class="org.springframework.core.io.support.PathMatchingResourcePatternResolver" />        </property>        <property name="mappingLocations">            <list>                <value>classpath*:cn/ruida/sms/portal/domain/mapper/*.hbm.xml                </value>                <value>classpath*:cn/ruida/mq/train/domain/mapper/*.hbm.xml</value>            </list>        </property>    </bean> 
5)配置事务
<!-- 事务配置 -->    <bean id="transactionManager"        class="org.springframework.orm.hibernate4.HibernateTransactionManager">        <property name="sessionFactory" ref="sessionFactory" />    </bean>    <!-- 显式配置DAO -->    <bean class="cn.ruida.framework.core.dao.Dao" id="dao">        <property name="sessionFactory" ref="sessionFactory" />    </bean>    <!-- 使用annotation定义事务 -->    <tx:annotation-driven transaction-manager="transactionManager"        proxy-target-class="true" />  
完整的application-dao.xml配置如下
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"    xmlns:task="http://www.springframework.org/schema/task" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"    xsi:schemaLocation="        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd        http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd ">    <!-- ===========================数据源 连接池==========================-->    <context:property-placeholder        ignore-unresolvable="true" location="classpath*:/application.properties" />    <bean id="stat-filter" class="com.alibaba.druid.filter.stat.StatFilter">        <property name="slowSqlMillis" value="1000" />        <property name="logSlowSql" value="true" />    </bean>    <!-- 第一:配置杭州的数据源 Start-->    <!-- 数据源配置, 使用德鲁伊连接池 -->    <!-- 配置一个父类数据源 -->    <bean id="dataSource_hz" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">      <!-- 基本属性 url、user、password -->        <property name="url" value="${hz.jdbc.url}" />        <property name="username" value="${hz.jdbc.username}" />        <property name="password" value="${hz.jdbc.password}" /><!-- 配置初始化大小、最小、最大 -->              <property name="initialSize" value="1" />        <property name="minIdle" value="1" />        <property name="maxActive" value="20" />        <!-- 配置获取连接等待超时的时间 -->        <property name="maxWait" value="60000" />        <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->        <property name="timeBetweenEvictionRunsMillis" value="60000" />        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->        <property name="minEvictableIdleTimeMillis" value="300000" />        <property name="validationQuery" value="SELECT 'x'" />        <property name="testWhileIdle" value="true" />        <property name="testOnBorrow" value="false" />        <property name="testOnReturn" value="false" />        <!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->        <property name="poolPreparedStatements" value="false" />        <property name="proxyFilters">            <list>                <ref bean="stat-filter" />            </list>        </property>    </bean>    <bean id="dataSource_tz" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">      <!-- 基本属性 url、user、password -->        <property name="url" value="${tz.jdbc.url}" />        <property name="username" value="${tz.jdbc.username}" />        <property name="password" value="${tz.jdbc.password}" />              <property name="initialSize" value="1" />        <property name="minIdle" value="1" />        <property name="maxActive" value="20" />        <!-- 配置获取连接等待超时的时间 -->        <property name="maxWait" value="60000" />        <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->        <property name="timeBetweenEvictionRunsMillis" value="60000" />        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->        <property name="minEvictableIdleTimeMillis" value="300000" />        <property name="validationQuery" value="SELECT 'x'" />        <property name="testWhileIdle" value="true" />        <property name="testOnBorrow" value="false" />        <property name="testOnReturn" value="false" />        <!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->        <property name="poolPreparedStatements" value="false" />        <property name="proxyFilters">            <list>                <ref bean="stat-filter" />            </list>        </property>    </bean>    <!-- 配置杭州的数据源 -->    <!-- <bean id="dataSource_hz" parent="parentDataSource">            </bean> -->    <!-- 配置台州的数据源 --><!--     <bean id="dataSource_tz" parent="parentDataSource">        基本属性 url、user、password            </bean> -->    <!-- 编写spring 配置文件的配置多数源映射关系 -->    <bean id="dataSource" class="cn.ruida.mq.train.product.datasource.DynamicDataSource" >      <property name="targetDataSources">        <map key-type="java.lang.String">         <entry value-ref="dataSource_hz" key="hzDataSource"></entry>         <entry value-ref="dataSource_tz" key="tzDataSource"></entry>        </map>      </property>      <property name="defaultTargetDataSource"  ref="dataSource_hz"></property>   </bean>       <!-- 配置sessionFactory -->    <bean id="sessionFactory"        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">        <property name="dataSource" ref="dataSource" />        <property name="hibernateProperties">            <props>                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>                <prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext                </prop>            </props>        </property>        <property name="resourceLoader">            <bean                class="org.springframework.core.io.support.PathMatchingResourcePatternResolver" />        </property>        <property name="mappingLocations">            <list>                <value>classpath*:cn/ruida/sms/portal/domain/mapper/*.hbm.xml                </value>                <value>classpath*:cn/ruida/mq/train/domain/mapper/*.hbm.xml</value>            </list>        </property>    </bean>    <!-- 事务配置 -->    <bean id="transactionManager"        class="org.springframework.orm.hibernate4.HibernateTransactionManager">        <property name="sessionFactory" ref="sessionFactory" />    </bean>    <!-- 显式配置DAO -->    <bean class="cn.ruida.framework.core.dao.Dao" id="dao">        <property name="sessionFactory" ref="sessionFactory" />    </bean>    <!-- 使用annotation定义事务 -->    <tx:annotation-driven transaction-manager="transactionManager"        proxy-target-class="true" />    <!--    <bean class="cn.ruida.sms.train.commons.dao.QryDao" id="qryDao">        <property name="sessionFactory" ref="sessionFactory" />    </bean>-->    <task:annotation-driven />    <task:scheduled-tasks>        <task:scheduled ref="productSchedule" method="pushMessage"            cron="0 51 17 * * ?" />    </task:scheduled-tasks>    </beans>  
至此,我们的多数据源的配置就完成了。怎样用呢,由于原因,只列举部分代码:
private List<EduRegion> getHTListEdu(Class clazz, HashMap<String, Object> map,            String delStatusName, int delStatus,String dataSourceType) {        //此句就是动态获取数据源        DataSourceContextHolder.setDataSourceType(dataSourceType);        String className = clazz.getSimpleName();        boolean flag = productService.isExistClassName(className);        List<EduRegion>  list= null;        if(flag){            Timestamp oldUpdate = productService.getPushUpdateTime(className);            Timestamp cTime = new Timestamp(System.currentTimeMillis());            list = productService.getList(clazz,delStatusName,delStatus,oldUpdate,cTime);                        productService.updatePushUpdateTime(className,cTime);        }else{            Timestamp cTime = new Timestamp(System.currentTimeMillis());             list = productService.getList(clazz,delStatusName,delStatus,null,cTime);             productService.addPushUpdateTime(className,cTime);        }        if(CollectionUtil.isEmpty(list)){            return list;        }        for(EduRegion er:list){            if(er==null){                continue;            }            long cityId = productService.queryCity(er.getSchoolyardId());            er.setCityId(cityId);        }        return list;    }  
















0 0