spring和mybatis集成(二) 设置spring的动态数据源

本文介绍了一种在Spring框架下实现数据库分库分表的方法。通过动态注册数据源和事务管理器,使得应用程序能够根据业务需求选择合适的数据库进行读写操作。此方案利用了MyBatis作为持久层框架,并通过ThreadLocal保存当前线程使用的数据源信息。
摘要由CSDN通过智能技术生成

项目中随着数据量的增多,对于关系型数据库最好的做法就是分库分表,而对于业务逻辑的开发这部分应该是透明的。

以下是对于分库时spring设置简单例子

1、配置一个默认的数据源bean(dataSource),事务控制(txManager),主要是方便注册bean时可以直接继承默认的配置

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="${url}" />
    <property name="username" value="${username}" />
    <property name="password" value="${password}"/>
</bean>

<pre name="code" class="html"><bean id="txManagerDefault" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
	<property name="dataSource" ref="dataSource" />
</bean>

 2、根据业务要求判断当前业务是否需要分库处理,如果需要分库指定的哪个数据库,注册当前数据源和事务控制的tx 

比如传入的参数cityID=010,可以根据cityID查询基本配置,判断取010是否需要分库,如果需要分库取出配置的url,username,password。

动态注册dataSource和txManager.代码如下

public class DynamicDataSourceContext implements ApplicationContextAware, ApplicationListener<ApplicationEvent>{

	private Logger logger = LoggerFactory.getLogger(DynamicDataSourceContext.class);
	
private ApplicationContext app; 
	
    @Override  
    public void setApplicationContext(ApplicationContext app)  
            throws BeansException {  
        this.app = app;  
    }  
    public void onApplicationEvent(ApplicationEvent event) {    
       //如果是容器刷新事件    
    }    
    /** 
     * 功能说明:生成一个新的DataSource
     * @param acf 
     * @param mapCustom 
     */  
    public boolean createDataSource(Map<String, String> dataMap) {
    	String dsName = dataMap.get(DataSourceConstant.DS_NAME);
    	String jdbcUrl = dataMap.get(DataSourceConstant.JDBC_URL);
    	String userName = dataMap.get(DataSourceConstant.USER_NAME);
    	String password = dataMap.get(DataSourceConstant.USER_PASSWORD);
    	if (StringUtils.isEmpty(dsName) || StringUtils.isEmpty(jdbcUrl) || StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)) {
    		logger.error(" params error, data [" + dataMap + "]");
    		return false;
    	}
    	logger.info(" registe dataSource data [" + dataMap + "]");
    	//判断dataSource是否存在,存在不需要注册
    	String dataSourceBeanName = getDataSource() + dsName;
    	if (app.containsBean(dataSourceBeanName)) {
    		logger.debug(" already contain dataSource [" + dataSourceBeanName + "]");
    		return true;
    	}
    	//开始注册一个新的dataSource的bean
    	DefaultListableBeanFactory acf = (DefaultListableBeanFactory)app.getAutowireCapableBeanFactory();
    	logger.info(" start registe dataSourceName [" + dataSourceBeanName + "]");
    	//继承自设置的默认的 dataSource,包括连接池等
    	BeanDefinition dataSourceBeanDef = new ChildBeanDefinition(getParentDataSource());
    	acf.registerBeanDefinition(dataSourceBeanName, dataSourceBeanDef);
    	BasicDataSource dbs = (BasicDataSource)app.getBean(dataSourceBeanName);
    	dbs.setUrl(jdbcUrl);
    	dbs.setUsername(userName);
    	dbs.setPassword(password);
    	//开始注册一个新的txManager的bean
    	String txManagerBeanName = getTxManager() + dsName;
    	if (app.containsBean(txManagerBeanName)) {
    		logger.debug(" already contain txManager [" + txManagerBeanName + "]");
    		return true;
    	}
    	logger.info(" start registe txManager [" + txManagerBeanName + "]");
    	BeanDefinition txBeanDef = new ChildBeanDefinition(getParentTxManager());
    	acf.registerBeanDefinition(txManagerBeanName, txBeanDef);
    	DataSourceTransactionManager txManager = (DataSourceTransactionManager)app.getBean(txManagerBeanName);
    	txManager.setDataSource(dbs);
    	
    	return true;
    }

3、注册新的DataSource成功之后,需要设置当前线程的Dataset为新注册的DataSource的Name

//设置当前线程执行的dataName
DynamicDataSourceHolder.setDataSource(name);

public class DynamicDataSourceHolder {
	
	private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();  
	  
    public static void setDataSource(String dataSource) {  
        Validate.notNull(dataSource, "必须指定路由的context");  
        contextHolder.set(dataSource);  
    }  
  
    public static String getDataSource() {  
        return contextHolder.get();  
    }
    
    public static void removeDataSource() {
    	contextHolder.remove();
    }
}

4、因为此处的事务是通过程序控制的,所以当需要打开事务时,需要从线程中的DataSource打开新的链接

<bean id="txManager" class="xxx.DynamicDataSourceTransactionManager"/>
    
    <tx:advice id="txAdvice" transaction-manager="txManager">
		<tx:attributes>
			<tx:method name="execute" isolation="DEFAULT" read-only="false" propagation="REQUIRED" rollback-for="Exception" />
		</tx:attributes>
	</tx:advice>

public class DynamicDataSourceTransactionManager implements PlatformTransactionManager {

	private Logger logger = LoggerFactory.getLogger(DynamicDataSourceTransactionManager.class);
	
	private PlatformTransactionManager getTargetTransactionManager() {
		String context = DynamicDataSourceHolder.getDataSource();
		PlatformTransactionManager routingManger = null;
		if (context != null) {
			//发现当前线程指定的连接池
			String txManagerName = DataSourceConstant.TX_PRE_NAME + context;
			logger.info(" txManagerName [" + context + "]");
			routingManger = ContextBeanFactory.getBean(txManagerName, PlatformTransactionManager.class);
		}
		if (routingManger == null) {
			routingManger = ContextBeanFactory.getBean(DataSourceConstant.TX_NAME_DEFAULT, PlatformTransactionManager.class);
		}
		return routingManger;
	}
	
	public void commit(TransactionStatus status) throws TransactionException {
		getTargetTransactionManager().commit(status);
	}

	public TransactionStatus getTransaction(TransactionDefinition definition)
			throws TransactionException {
		return getTargetTransactionManager().getTransaction(definition);
	}

	public void rollback(TransactionStatus status) throws TransactionException {
		getTargetTransactionManager().rollback(status);
	}

}

5、对于数据库的操作是交由mybatis来操作的。所以需要更改一个mybatis的sessionFactory设置,让mybatis的transactionFactory由自定义的管理

  <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  	<property name="dataSource" ref="dataSource"></property>
  	<property name="mapperLocations" value="classpath*:platform/service/mybatis/*mysql.xml"/>
  	<property name="transactionFactory" ref="dynamicDatasourceTransactionFactory"/>
  </bean>
  
  <bean id="dynamicDatasourceTransactionFactory" class="xxxx.DynamicDatasourceSpringManagedTransactionFactory"/>
  

public class DynamicDatasourceSpringManagedTransactionFactory extends SpringManagedTransactionFactory {

	private Logger logger = LoggerFactory.getLogger(DynamicDatasourceSpringManagedTransactionFactory.class);
	@Override
	public Transaction newTransaction(DataSource dataSource, TransactionIsolationLevel level, boolean autoCommit) {
		//当前线程指定了数据库链接
		String context = DynamicDataSourceHolder.getDataSource();
		if (context != null) {
			logger.info(" thread context [" + context + "]");
		} else {
			return super.newTransaction(dataSource, level, autoCommit);
		}
		String newDataSourceName = DataSourceConstant.DS_PRE_NAME + context;
		DataSource newDataSource = (DataSource)ContextBeanFactory.getBean(newDataSourceName);
		if (newDataSource == null) {
			logger.error(" not found datasource name [" + newDataSourceName + "]");
			return super.newTransaction(dataSource, level, autoCommit);
		}
		return super.newTransaction(newDataSource, level, autoCommit);
	}
}

总结:

生成一个新数据源(dataSource),如果spring的容器不存在,注册一个新的数据源。由业务执行的线程执有当前的数据源的id名称,之后所有和dataSource有关的操作全部用线程中存在的数据源处理。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值