`
aaron7524
  • 浏览: 63511 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Spring 动态设置数据源

    博客分类:
  • java
阅读更多
Spring2.0.1以后的版本已经支持配置多数据源,并且可以在运行的时候动态加载不同的数据源。通过继承AbstractRoutingDataSource就可以实现多数据源的动态转换。目前做的项目就是需要访问12个数据源,每个数据源的表结构都是相同的,所以要求数据源的变动对于编码人员来说是透明,也就是说同样SQL语句在不同的环境下操作的数据库是不一样的。具体的配置如下:
一、首先需要写一个静态的键值对照类:


代码
package cn.com.xinli.ccp.dynamicds;    
   
public class DataSourceMap {    
    public static final String Admin="Admin";    
    public static final String Yxh = "Yxh";    
} 




这个类主要在使用的时候当作获得数据源的标志使用。
二、建立一个获得和设置上下文的类:


代码
package cn.com.xinli.ccp.dynamicds;    
   
public class CustomerContextHolder {    
    private static final ThreadLocal contextHolder =     
        new ThreadLocal();    
        
    public static void setCustomerType(String customerType) {    
      contextHolder.set(customerType);    
    }    
        
    public static String getCustomerType() {    
      return (String) contextHolder.get();    
    }    
        
    public static void clearCustomerType() {   
      contextHolder.remove();
    }    
   
}  


这个主要负责设置上下文环境和获得上下文环境。
三、建立动态数据源类,这个类必须继承AbstractRoutingDataSource:

代码
package cn.com.xinli.ccp.dynamicds;    
   
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;    
   
public class DynamicDataSource extends AbstractRoutingDataSource {    
   
    protected Object determineCurrentLookupKey() {    
        // TODO Auto-generated method stub    
        return CustomerContextHolder.getCustomerType();    
    }    
   
} 


这个类实现了determineCurrentLookupKey方法,该方法返回一个Object,一般是返回字符串,也可以是枚举类型。该方法中直接使用了CustomerContextHolder.getCustomerType()方法获得上下文环境并直接返回。
四、编写spring的配置文件配置数据源

代码
<bean id="parentDataSource"   
            class="org.springframework.jdbc.datasource.DriverManagerDataSource">   
            <property name="driverClassName">   
                <value>COM.ibm.db2.jdbc.net.DB2Driver</value>   
            </property>   
            <property name="url">   
                <value>jdbc:db2:127.0.0.1:TEST</value>   
            </property>   
    </bean>   
        
    <bean id="adminDataSource" parent="parentDataSource">   
        <property name="username" value="admin"/>   
        <property name="password" value="master997mb"/>   
    </bean>   
        
    <bean id="yxhDataSource" parent="parentDataSource">   
        <property name="username" value="yxh"/>   
        <property name="password" value="yxh"/>   
    </bean>  


在这个配置中可以看到首先有个parentDataSource,这个主要配置一些数据源的公用信息,项目中都是链接DB2数据库;adminDataSource和yxhDataSource是根据不同需要配置的个性化信息,但都必须加parent属性,值为parentDataSource。这样就配置好了2个数据源信息。当然如果链接的多数据源是不同类型的两个数据库,那么parentDataSource就可以不要了,直接配置两个不同的数据源链接就可以了。
五、编写spring配置文件配置多数据源映射关系

代码
<bean id="dataSource" class="cn.com.xinli.ccp.dynamicds.DynamicDataSource">   
       <property name="targetDataSources">   
          <map key-type="java.lang.String">   
             <entry key="Yxh" value-ref="yxhDataSource"/>   
          </map>   
       </property>   
       <property name="defaultTargetDataSource" ref="adminDataSource"/>   
    </bean>  


在这个配置中第一个property属性配置目标数据源,<map key-type="java.lang.String">中的key-type必须要和静态键值对照类DataSourceMap中的值的类型相同;<entry key="Yxh" value-ref="yxhDataSource"/>中key的值必须要和静态键值对照类中的值相同,如果有多个值,可以配置多个<entry>标签。第二个property属性配置默认的数据源。
六、配置hibernate。
Hibernate的配置和普通的hibernate、spring结合的配置一样

代码
<bean id="sessionFactory"   
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">   
        <!-- to override, use the "SpringDatasourceConfig" snippet in your project -->   
        <property name="dataSource">   
            <ref local="dataSource" />   
        </property>   
        <property name="mappingResources">   
            <list>   
                <value>   
                    cn/com/xinli/ccp/entity/User.hbm.xml    
                </value>   
                <value>   
                    cn/com/xinli/ccp/entity/Test.hbm.xml    
                </value>   
            </list>   
        </property>   
        <property name="hibernateProperties">   
            <props>   
                <prop key="hibernate.dialect">   
                    org.hibernate.dialect.DB2Dialect    
                </prop>   
                    
                <prop key="hibernate.show_sql">true</prop>   
                <prop key="hibernate.use_outer_join">true</prop>   
                <prop key="hibernate.jdbc.batch_size">50</prop>   
                <prop key="hibernate.jdbc.fetch_size">5</prop>   
                <prop key="hibernate.connection.pool_size">2</prop>   
                <prop key="hibernate.connection.autocommit">false</prop>   
                <prop key="hibernate.cache.use_query_cache">false</prop>   
                <prop key="hibernate.max_fetch_depth">1</prop>   
                <prop key="hibernate.bytecode.use_reflection_optimizer">true</prop>   
            </props>   
        </property>   
    </bean>   
   
<bean id="mydao" class="cn.com.xinli.ccp.dao.HibernateBaseDao">   
        <property name="sessionFactory">   
            <ref local="sessionFactory" />   
        </property>   
    </bean>  

关于dao的代码这里就省略了。
七、配置结束,可以使用了。

代码
public class DaoTest extends TestCase {    
   
    public void testSave() throws Exception{    
        CustomerContextHolder.setCustomerType(DataSourceMap.Admin);//设置数据源    
        //hibernate创建实体    
        Test test = new Test();    
        test.setTest("22222222");    
            
        mydao.save(test);//使用dao保存实体    
            
        CustomerContextHolder.setCustomerType(DataSourceMap.Yxh);//设置为另一个数据源    
            
        mydao.save(test);//使用dao保存实体到另一个库中    
            
    }    
}  

在项目中对于编码人员对多数据源的切换可以做成透明的,操作同样的dao,就可以访问不同的数据库
补充:使用filter设置数据源
public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException     
    {     
       HttpServletRequest httpRequest = (HttpServletRequest) request;     
       Object dataSourceName=httpRequest.getSession().getAttribute("currentDataSource");     
           if(dataSourceName!=null&&!"".equals(dataSourceName))     
           {     
              String name = dataSourceName.toString();     
              //System.out.println("使数据源"+name);
              CustomerContextHolder.setCustomerType(name);
           }     
           else     
           {  
        	   CustomerContextHolder.setCustomerType("publicDataSource");
              //System.out.println("使用默认数据源");     
           }     
       chain.doFilter(request, response);
       CustomerContextHolder.clearCustomerType();
    }
分享到:
评论
2 楼 sunkiller 2011-11-10  
而最后的filter里面Object dataSourceName=httpRequest.getSession().getAttribute("currentDataSource"); 还是需要程序员把currentDataSource放入session

这个要把currentDatasource放到session里才能做动态切换,总不能切换还要退出系统关闭IE。
1 楼 xugq035 2009-08-08  
最后那里:在项目中对于编码人员对多数据源的切换可以做成透明的

这个透明是怎样做?怎样才能令程序员连CustomerContextHolder.setCustomerType(DataSourceMap.Admin);这一句都不用做,或者通过配置文件实现?

而最后的filter里面Object dataSourceName=httpRequest.getSession().getAttribute("currentDataSource"); 还是需要程序员把currentDataSource放入session

相关推荐

Global site tag (gtag.js) - Google Analytics