spring框架多数据源切换问题的解决

来源:互联网 发布:淘宝怎么退换货 编辑:程序博客网 时间:2024/05/29 07:08

Spring动态配置多数据源,即在大型应用中对数据进行切分,并且采用多个数据库实例进行管理,这样可以有效提高系统的水平伸缩性。而这样的方案就会不同于常见的单一数据实例的方案,这就要程序在运行时根据当时的请求及系统状态来动态的决定将数据存储在哪个数据库实例中,以及从哪个数据库提取数据。

Spring配置多数据源的方式和具体使用过程。 
Spring对于多数据源,以数据库表为参照,大体上可以分成两大类情况: 
一是,表级上的跨数据库。即,对于不同的数据库却有相同的表(表名和表结构完全相同)。 
二是,非表级上的跨数据库。即,多个数据源不存在相同的表。

1、根据用户的选择,使用不同的数据源。

2、解决思路锁定:将sessionFactory的属性dataSource设置成不同的数据源,以达到切换数据源的目的。

3、问题产生:因为整个项目用的几乎都是单例模式,当多个用户并发访问数据库的时候,会产生资源争夺的问题。即项目启动时候,所有的bean都被装载到内存,并且每个bean都只有一个对象。正因为只有一个对象,所有的对象属性就如同静态变量(静态变量跟单例很相似,常用静态来实现单例)。整个项目系统的dataSource只有一个,如果很多用户不断的去改变dataSource的值,那必然会出现资源的掠夺问题,造成系统隐患。

4、多资源共享解决思路:同一资源被抢夺的时候,通常有两种做法,a、以时间换空间 b、以空间换时间。

5、线程同步机制就是典型的“以时间换空间”,采用排队稍等的方法,一个个等待,直到前面一个用完,后面的才跟上,多人共用一个变量,用synchronized锁定排队。   

6、“ThreadLocal”就是典型的“以空间换时间”,她可以为每一个人提供一份变量,因此可以同时访问并互不干扰。

7、言归正传:sessionFactory的属性dataSource设置成不用的数据源,首先不能在配置文件中写死,我们必须为她单独写一个类,让她来引用这个类,在这个类中再来判断我们到底要选择哪个数据源。

 

spring + mybatis 多数据源切换

DbContextHolder.java

Java代码  收藏代码
  1. package com.easyway.stage.commons;  
  2.   
  3. public class DbContextHolder  
  4. {  
  5.   
  6.     // ThreadLocal是线程安全的,并且不能在多线程之间共享。  
  7.     private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();  
  8.   
  9.     public static void setDbType(String dbType)  
  10.     {  
  11.         contextHolder.set(dbType);  
  12.     }  
  13.   
  14.     public static String getDbType()  
  15.     {  
  16.         return ((String) contextHolder.get());  
  17.     }  
  18.   
  19.     public static void clearDbType()  
  20.     {  
  21.         contextHolder.remove();  
  22.     }  
  23.   
  24. }  

MultiDataSource.java

Java代码  收藏代码
  1. package com.easyway.stage.commons;  
  2.   
  3. import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;  
  4.   
  5. public class MultiDataSource extends AbstractRoutingDataSource  
  6. {  
  7.   
  8.     @Override  
  9.     protected Object determineCurrentLookupKey()  
  10.     {  
  11.         return  DbContextHolder.getDbType();  
  12.     }  
  13.   
  14. }  

applicationContext.xml

Xml代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans  
  3.     xmlns="http://www.springframework.org/schema/beans"  
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"  
  5.     xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"  
  6.     xmlns:context="http://www.springframework.org/schema/context"  
  7.     xsi:schemaLocation="         
  8.       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  9.       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd  
  10.       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd  
  11.       http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd  
  12.       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">  
  13.           
  14.     <context:annotation-config/>  
  15.   
  16.     <!-- 数据源 -->    
  17.     <bean id="parentDataSource" class="com.alibaba.druid.pool.DruidDataSource">  
  18.         <!-- 配置初始化大小、最小、最大 -->  
  19.         <property name="initialSize" value="1" />  
  20.         <property name="maxActive" value="20" />   
  21.         <property name="minIdle" value="1" />  
  22.           
  23.         <!-- 配置获取连接等待超时的时间60s -->  
  24.         <property name="maxWait" value="60000" />   
  25.           
  26.         <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->  
  27.         <property name="timeBetweenEvictionRunsMillis" value="60000" />  
  28.         <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->    
  29.         <property name="minEvictableIdleTimeMillis" value="300000" />    
  30.          
  31.         <property name="validationQuery" value="SELECT 'x'" />    
  32.         <property name="testWhileIdle" value="true" />    
  33.         <property name="testOnBorrow" value="false" />    
  34.         <property name="testOnReturn" value="false" />    
  35.           
  36.         <!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->  
  37.         <property name="poolPreparedStatements" value="true" />  
  38.         <property name="maxPoolPreparedStatementPerConnectionSize" value="20" />  
  39.           
  40.         <!-- 配置监控统计拦截的filters -->  
  41.         <property name="filters" value="wall,stat,slf4j" />  
  42.           
  43.         <!-- 对于长时间不使用的连接强制关闭  -->  
  44.         <property name="removeAbandoned" value="true" />  
  45.         <!-- 超过30分钟开始关闭空闲连接 -->  
  46.         <property name="removeAbandonedTimeout" value="1800" />   
  47.         <!-- 关闭abanded连接时输出错误日志 -->   
  48.         <property name="logAbandoned" value="true" />    
  49.     </bean>    
  50.     <bean id="local" parent="parentDataSource" init-method="init" destroy-method="close">      
  51.         <property name="url" value="${local.jdbc.url}" />    
  52.         <property name="username" value="${local.jdbc.username}" />    
  53.         <property name="password" value="${local.jdbc.password}" />      
  54.     </bean>  
  55.     <bean id="server" parent="parentDataSource" init-method="init" destroy-method="close">      
  56.         <property name="url" value="${jdbc.url}" />    
  57.         <property name="username" value="${jdbc.username}" />    
  58.         <property name="password" value="${jdbc.password}" />      
  59.     </bean>  
  60.   
  61.     <bean id="dataSource" class="com.autrade.stage.commons.MultiDataSource">  
  62.         <property name="targetDataSources">  
  63.             <map key-type="java.lang.String">  
  64.                 <entry value-ref="local" key="local"></entry>  
  65.                 <entry value-ref="server" key="server"></entry>  
  66.             </map>  
  67.         </property>  
  68.         <!-- 默认使用server的数据源 -->  
  69.         <property name="defaultTargetDataSource" ref="server"></property>  
  70.     </bean>    
  71.   
  72.     <!-- MyBatis -->  
  73.     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
  74.         <property name="dataSource" ref="dataSource" />  
  75.         <property name="configLocation" value="classpath:resources/mybatis/myBatisConfig.xml" />  
  76.         <property name="mapperLocations" value="classpath:resources/mybatis/mapper/*.xml"/>  
  77.     </bean>  
  78.     <bean class="org.mybatis.spring.SqlSessionTemplate">  
  79.       <constructor-arg ref="sqlSessionFactory"/>  
  80.     </bean>  
  81.     <!-- MyBatis -->  
  82.       
  83.     <!-- 配置事务管理对象-->  
  84.     <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
  85.         <property name="dataSource" ref="dataSource"/>  
  86.     </bean>  
  87.     <!-- 将所有具有@Transactional注解的Bean自动配置为声明式事务支持 -->  
  88.     <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>  
  89.   
  90.     <!-- 自定义的拦截器 -->  
  91.     <bean id="methodAdvisor" class="com.easyway.app.interceptor.InjectorManager" />  
  92.   
  93.     <aop:config proxy-target-class="true">  
  94.         <aop:pointcut id="baseMethods"  
  95.             expression="execution(* com.easyway.app.service..*.*(..))" />  
  96.         <aop:advisor advice-ref="methodAdvisor" pointcut-ref="baseMethods" />  
  97.     </aop:config>  
  98.         
  99. </beans>  

 

Test.java测试类

Java代码  收藏代码
  1. package com.easyway.stage.test;  
  2.   
  3. import javax.sql.DataSource;  
  4.   
  5. import org.apache.ibatis.session.SqlSession;  
  6. import org.apache.ibatis.session.SqlSessionFactory;  
  7. import org.mybatis.spring.SqlSessionFactoryBean;  
  8. import org.springframework.context.ApplicationContext;  
  9. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  10. import org.springframework.core.io.FileSystemResource;  
  11. import org.springframework.core.io.Resource;  
  12.   
  13. import com.easyway.stage.commons.DbContextHolder;  
  14.   
  15. public class Test  
  16. {  
  17.   
  18.     /** 
  19.      * @param args 
  20.      */  
  21.     public static void main(String[] args)  
  22.     {  
  23.         ApplicationContext appContext = new ClassPathXmlApplicationContext("client-beans.xml");  
  24.   
  25.         DbContextHolder.setDbType("local");  
  26.         String res = "resources/mybatis/myBatisConfig.xml";  
  27.         DataSource datasource = (DataSource) appContext.getBean("dataSource");  
  28.   
  29.         SqlSessionFactoryBean bean = new SqlSessionFactoryBean();  
  30.         bean.setDataSource(datasource);  
  31.         Resource resource = new FileSystemResource(res);  
  32.         bean.setConfigLocation(resource);  
  33.         try  
  34.         {  
  35.             SqlSessionFactory sessionfactory = bean.getObject();  
  36.             SqlSession session = sessionfactory.openSession();  
  37.             User user = session.selectOne("com.easyway.mybatis.mapper.findOne");  
  38.             System.out.println(user.getName());  
  39.         }  
  40.         catch (Exception e)  
  41.         {  
  42.             e.printStackTrace();  
  43.         }  
  44.   
  45.         DbContextHolder.setDbType("server");  
  46.         String res1 = "resources/mybatis/myBatisConfig.xml";  
  47.         DataSource datasource1 = (DataSource) appContext.getBean("dataSource");  
  48.   
  49.         SqlSessionFactoryBean bean1 = new SqlSessionFactoryBean();  
  50.         bean1.setDataSource(datasource1);  
  51.         Resource resource1 = new FileSystemResource(res1);  
  52.         bean1.setConfigLocation(resource1);  
  53.   
  54.         try  
  55.         {  
  56.             SqlSessionFactory sessionfactory = bean.getObject();  
  57.             SqlSession session = sessionfactory.openSession();  
  58.             User user = session.selectOne("com.easyway.mybatis.mapper.findOne");  
  59.             System.out.println(user.getName());  
  60.         }  
  61.         catch (Exception e)  
  62.         {  
  63.             e.printStackTrace();  
  64.         }  
  65.   
  66.     }  
  67.   
  68. }  
原创粉丝点击