项目中我们经常会遇到多数据源的问题,尤其是数据同步或定时任务等项目更是如此。多数据源让人最头痛的,不是配置多个数据源,而是如何能灵活动态的切换数据源。例如在一个spring和hibernate的框架的项目中,我们在spring配置中往往是配置一个dataSource来连接数据库,然后绑定给sessionFactory,在dao层代码中再指定sessionFactory来进行数据库操作。
正如上图所示,每一块都是指定绑死的,如果是多个数据源,也只能是下图中那种方式。
可看出在Dao层代码中写死了两个SessionFactory,这样日后如果再多一个数据源,还要改代码添加一个SessionFactory,显然这并不符合开闭原则。
那么正确的做法应该是
先说一下我的思路:
首先做一个创建数据源配置文件的类,专门用于创建数据源xml配置,叫ConfigFileCreator.java
其次,编写一个动态加载刚才创建的配置文件的类,叫 DynamicLoadBean.java。至此,创建的数据源到内存中已经完成。
第三,重点编写这个DynamicDataSource.java,该类主要是用来实现动态切换数据源,并通知容器。在这一块我选择了修改,AbstractRoutingDataSource.java,编写一个支持添加数据源对象的方法public void addDataSource(Object key,Object dataSource)
第四,写例子来测试
实现过程如下:
1.bean.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>2.AbstractRoutingDataSource.class 修改的部分
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
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://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<!-- 自动扫描与装配bean -->
<context:component-scan base-package="qilin"></context:component-scan>
<!-- 使用外部的配置文件 -->
<context:property-placeholder location="classpath:jdbc.properties" />
<bean id="defaultDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!-- 数据库连接信息 -->
<property name="jdbcUrl" value="${jdbcUrl}"></property>
<property name="driverClass" value="${driverClass}"></property>
<property name="user" value="${username}"></property>
<property name="password" value="${password}"></property>
</bean>
<bean id="dataSourceA" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!-- 数据库连接信息 -->
<property name="jdbcUrl" value="jdbc:mysql:///dynamictest"></property>
<property name="driverClass" value="${driverClass}"></property>
<property name="user" value="${username}"></property>
<property name="password" value="${password}"></property>
</bean>
<bean id="dynamicdatasource" class="qilin.utils.DynamicDataSource">
<property name="targetDataSources">
<map key-type="java.lang.String">
<entry key="defaultDataSource" value-ref="defaultDataSource" />
<entry key="dataSourceA" value-ref="dataSourceA" />
</map>
</property>
<property name="defaultTargetDataSource" ref="defaultDataSource" />
</bean>
<!-- 配置SessionFactory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dynamicdatasource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.hbm2ddl.auto">none</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">false</prop>
<prop key="hibernate.temp.use_jdbc_metadata_defaults">false</prop>
</props>
</property>
<!-- 注解方式配置 -->
<property name="annotatedClasses">
<list>
<value>qilin.entity.Student</value>
</list>
</property>
</bean>
<!-- 配置声明式事务管理,采用基于注解的方式 -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="dynamicLoadBean" class="qilin.utils.DynamicLoadBean"></bean>
</beans>
/**@author qilin**/3.DynamicDataSource.class 这个类中有一个地方需要注意,当我们添加数据,切换了数据源,要通知当前spring容器,需要调用父类的super.afterPropertiesSet();方法
public void addDataSource(Object key,Object dataSource){
this.targetDataSources.put(key, dataSource);
setTargetDataSources(this.targetDataSources);
}
package qilin.utils;4.动态加载数据源配置文件DynamicLoadBean.class
import java.util.Map;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.jdbc.datasource.lookup.DataSourceLookup;
public class DynamicDataSource extends AbstractRoutingDataSource {
/*
* 该方法必须要重写 方法是为了根据数据库标示符取得当前的数据库
*/
@Override
public Object determineCurrentLookupKey() {
return DataSourceContextHolder.getDataSourceName();
}
@Override
public void setDataSourceLookup(DataSourceLookup dataSourceLookup) {
super.setDataSourceLookup(dataSourceLookup);
}
@Override
public void setDefaultTargetDataSource(Object defaultTargetDataSource) {
super.setDefaultTargetDataSource(defaultTargetDataSource);
}
@Override
public void setTargetDataSources(Map targetDataSources) {
super.setTargetDataSources(targetDataSources);
//重点
super.afterPropertiesSet();
}
}
package qilin.utils;5.DataSourceContextHolder.class
import java.io.IOException;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.ChildBeanDefinition;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.ResourceEntityResolver;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
/**
* 动�?�加载数据源
* @author qilin
*
*/
public class DynamicLoadBean implements ApplicationContextAware {
private ConfigurableApplicationContext applicationContext = null;
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
this.applicationContext = (ConfigurableApplicationContext) applicationContext;
}
public ConfigurableApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* 1.配置文件的位置固�?
* 2.配置文件中bean的名字已�?
* @param configLocationString
*/
public void loadBean(String fileName)
{
XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader((BeanDefinitionRegistry)getApplicationContext().getBeanFactory());
beanDefinitionReader.setResourceLoader(getApplicationContext());
beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(getApplicationContext()));
try
{
beanDefinitionReader.loadBeanDefinitions(getApplicationContext().getResources(fileName));
} catch (BeansException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void registBean(String beanName, String parentName) {
DefaultListableBeanFactory fcy = (DefaultListableBeanFactory)applicationContext.getAutowireCapableBeanFactory();
BeanDefinition beanDefinition = new ChildBeanDefinition(parentName);
fcy.registerBeanDefinition(beanName, beanDefinition);
}
}
package qilin.utils;
public class DataSourceContextHolder {
private static final ThreadLocal contextHolder=new ThreadLocal();
public static void setDataSourceType(String dataSourceName){
contextHolder.set(dataSourceName);
}
public static String getDataSourceName(){
return (String) contextHolder.get();
}
public static void clearDataSourceType(){
contextHolder.remove();
}
}
5.测试代码
package junit;
import java.util.HashMap;
import java.util.Map;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import qilin.entity.Student;
import qilin.service.StuService;
import qilin.utils.DataSourceContextHolder;
import qilin.utils.DynamicDataSource;
import qilin.utils.DynamicLoadBean;
public class Test {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
StuService stuService = (StuService) ac.getBean("stuServiceImpl");
Student stu = new Student();
stu.setStuName("qilin");
stuService.save(stu);
DataSourceContextHolder.setDataSourceType("dataSourceA");
Student _stu = new Student();
_stu.setStuName("_qilin1");
stuService.save(_stu);
//创建一个数据源
DynamicLoadBean dynamicBeanLoad =(DynamicLoadBean)ac.getBean("dynamicLoadBean");
dynamicBeanLoad.loadBean("classpath:mos/qqq.xml");
ComboPooledDataSource dataSource = (ComboPooledDataSource) ac.getBean("qqq");
System.err.println(dataSource.getDriverClass());
DynamicDataSource dynamicDataSource = (DynamicDataSource) ac.getBean("dynamicdatasource");
// Map<String, ComboPooledDataSource> targetDataSources = new HashMap<String, ComboPooledDataSource>();
// targetDataSources.put("qqq", dataSource);
// Map<Object, Object> targetDataSources = dynamicDataSource.getTargetDataSources();
// targetDataSources.put("qqq", dataSource);
// dynamicDataSource.setTargetDataSources(targetDataSources);
// dynamicDataSource.setDefaultTargetDataSource(dataSource);
dynamicDataSource.addDataSource("qqq", dataSource);
DataSourceContextHolder.setDataSourceType("qqq");
Student __stu = new Student();
__stu.setStuName("qilin2");
stuService.save(__stu);
}
}
切换数据源就一句话搞定 DataSourceContextHolder.setDataSourceType("qqq");
下载链接http://download.csdn.net/detail/qi_lin70/6778247
有什么不妥之处,还望指教。共同学习,共同进步!