欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Spring + Mybatis 項目實現(xiàn)動態(tài)切換數(shù)據(jù)源實例詳解

 更新時間:2017年04月22日 14:52:18   作者:FlyHeLanMan  
這篇文章主要介紹了Spring + Mybatis 項目實現(xiàn)動態(tài)切換數(shù)據(jù)源的相關(guān)資料,需要的朋友參考下吧

項目背景:項目開發(fā)中數(shù)據(jù)庫使用了讀寫分離,所有查詢語句走從庫,除此之外走主庫。

最簡單的辦法其實就是建兩個包,把之前數(shù)據(jù)源那一套配置copy一份,指向另外的包,但是這樣擴(kuò)展很有限,所有采用下面的辦法。

參考了兩篇文章如下:

http://www.dbjr.com.cn/article/111840.htm

http://www.dbjr.com.cn/article/111842.htm

這兩篇文章都對原理進(jìn)行了分析,下面只寫自己的實現(xiàn)過程其他不再敘述。

實現(xiàn)思路是:

第一步,實現(xiàn)動態(tài)切換數(shù)據(jù)源:配置兩個DataSource,配置兩個SqlSessionFactory指向兩個不同的DataSource,兩個SqlSessionFactory都用一個SqlSessionTemplate,同時重寫Mybatis提供的SqlSessionTemplate類,最后配置Mybatis自動掃描。

第二步,利用aop切面,攔截dao層所有方法,因為dao層方法命名的特點,比如所有查詢sql都是select開頭,或者get開頭等等,攔截這些方法,并把當(dāng)前數(shù)據(jù)源切換至從庫。

spring中配置如下:

主庫數(shù)據(jù)源配置:

 <bean id="masterDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">2 <property name="driverClass" value="${master_mysql_jdbc_driver}" />
 <property name="jdbcUrl" value="${master_mysql_jdbc_url}" />
 <property name="user" value="${master_mysql_jdbc_user}" />
 <property name="password" value="${master_mysql_jdbc_password}" />
 </bean>

從庫數(shù)據(jù)源配置:

 <bean id="masterDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
 <property name="driverClass" value="${slave_mysql_jdbc_driver}" />
 <property name="jdbcUrl" value="${slave_mysql_jdbc_url}" />
 <property name="user" value="${slave_mysql_jdbc_user}" />
 <property name="password" value="${slave_mysql_jdbc_password}" />
 </bean>

主庫SqlSessionFactory配置:

 <bean id="masterSqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
 <property name="dataSource" ref="masterDataSource" />
 <property name="mapperLocations" value="classpath:com/sincetimes/slg/dao/*.xml"/>
 </bean>

從庫SqlSessionFactory配置:

 <bean id="slaveSqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
 <property name="dataSource" ref="slaveDataSource" />
 <property name="mapperLocations" value="classpath:com/sincetimes/slg/dao/*.xml"/>
 </bean>

兩個SqlSessionFactory使用同一個SqlSessionTemplate配置:

 <bean id="MasterAndSlaveSqlSessionTemplate" class="com.sincetimes.slg.framework.core.DynamicSqlSessionTemplate">
 <constructor-arg index="0" ref="masterSqlSessionFactory" />
 <property name="targetSqlSessionFactorys">
 <map> 
 <entry value-ref="masterSqlSessionFactory" key="master"/> 
 <entry value-ref="slaveSqlSessionFactory" key="slave"/> 
 </map> 
 </property>
 </bean>

配置Mybatis自動掃描dao

 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
 <property name="basePackage" value="com.sincetimes.slg.dao" />
 <property name="sqlSessionTemplateBeanName" value="MasterAndSlaveSqlSessionTemplate" />
 </bean>

自己重寫了SqlSessionTemplate代碼如下:

package com.sincetimes.slg.framework.core;
import static java.lang.reflect.Proxy.newProxyInstance;
import static org.apache.ibatis.reflection.ExceptionUtil.unwrapThrowable;
import static org.mybatis.spring.SqlSessionUtils.closeSqlSession;
import static org.mybatis.spring.SqlSessionUtils.getSqlSession;
import static org.mybatis.spring.SqlSessionUtils.isSqlSessionTransactional;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.exceptions.PersistenceException;
import org.apache.ibatis.executor.BatchResult;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.MyBatisExceptionTranslator;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.dao.support.PersistenceExceptionTranslator;
import org.springframework.util.Assert;
import com.sincetimes.slg.framework.util.SqlSessionContentHolder;
/**
 * 
 * TODO 重寫SqlSessionTemplate
 * @author ccg
 * @version 1.0
 * Created 2017年4月21日 下午3:15:15
 */
public class DynamicSqlSessionTemplate extends SqlSessionTemplate {
 private final SqlSessionFactory sqlSessionFactory;
 private final ExecutorType executorType;
 private final SqlSession sqlSessionProxy;
 private final PersistenceExceptionTranslator exceptionTranslator;
 private Map<Object, SqlSessionFactory> targetSqlSessionFactorys;
 private SqlSessionFactory defaultTargetSqlSessionFactory;
 public void setTargetSqlSessionFactorys(Map<Object, SqlSessionFactory> targetSqlSessionFactorys) {
 this.targetSqlSessionFactorys = targetSqlSessionFactorys;
 }
 public Map<Object, SqlSessionFactory> getTargetSqlSessionFactorys(){
 return targetSqlSessionFactorys;
 }
 public void setDefaultTargetSqlSessionFactory(SqlSessionFactory defaultTargetSqlSessionFactory) {
 this.defaultTargetSqlSessionFactory = defaultTargetSqlSessionFactory;
 }
 public DynamicSqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
 this(sqlSessionFactory, sqlSessionFactory.getConfiguration().getDefaultExecutorType());
 }
 public DynamicSqlSessionTemplate(SqlSessionFactory sqlSessionFactory, ExecutorType executorType) {
 this(sqlSessionFactory, executorType, new MyBatisExceptionTranslator(sqlSessionFactory.getConfiguration()
 .getEnvironment().getDataSource(), true));
 }
 public DynamicSqlSessionTemplate(SqlSessionFactory sqlSessionFactory, ExecutorType executorType,
 PersistenceExceptionTranslator exceptionTranslator) {
 super(sqlSessionFactory, executorType, exceptionTranslator);
 this.sqlSessionFactory = sqlSessionFactory;
 this.executorType = executorType;
 this.exceptionTranslator = exceptionTranslator;
 this.sqlSessionProxy = (SqlSession) newProxyInstance(
 SqlSessionFactory.class.getClassLoader(),
 new Class[] { SqlSession.class }, 
 new SqlSessionInterceptor());
 this.defaultTargetSqlSessionFactory = sqlSessionFactory;
 }
 @Override
 public SqlSessionFactory getSqlSessionFactory() {
 SqlSessionFactory targetSqlSessionFactory = targetSqlSessionFactorys.get(SqlSessionContentHolder.getContextType());
 if (targetSqlSessionFactory != null) {
 return targetSqlSessionFactory;
 } else if (defaultTargetSqlSessionFactory != null) {
 return defaultTargetSqlSessionFactory;
 } else {
 Assert.notNull(targetSqlSessionFactorys, "Property 'targetSqlSessionFactorys' or 'defaultTargetSqlSessionFactory' are required");
 Assert.notNull(defaultTargetSqlSessionFactory, "Property 'defaultTargetSqlSessionFactory' or 'targetSqlSessionFactorys' are required");
 }
 return this.sqlSessionFactory;
 }
 @Override
 public Configuration getConfiguration() {
 return this.getSqlSessionFactory().getConfiguration();
 }
 public ExecutorType getExecutorType() {
 return this.executorType;
 }
 public PersistenceExceptionTranslator getPersistenceExceptionTranslator() {
 return this.exceptionTranslator;
 }
 /**
 * {@inheritDoc}
 */
 public <T> T selectOne(String statement) {
 return this.sqlSessionProxy.<T> selectOne(statement);
 }
 /**
 * {@inheritDoc}
 */
 public <T> T selectOne(String statement, Object parameter) {
 return this.sqlSessionProxy.<T> selectOne(statement, parameter);
 }
 /**
 * {@inheritDoc}
 */
 public <K, V> Map<K, V> selectMap(String statement, String mapKey) {
 return this.sqlSessionProxy.<K, V> selectMap(statement, mapKey);
 }
 /**
 * {@inheritDoc}
 */
 public <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey) {
 return this.sqlSessionProxy.<K, V> selectMap(statement, parameter, mapKey);
 }
 /**
 * {@inheritDoc}
 */
 public <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey, RowBounds rowBounds) {
 return this.sqlSessionProxy.<K, V> selectMap(statement, parameter, mapKey, rowBounds);
 }
 /**
 * {@inheritDoc}
 */
 public <E> List<E> selectList(String statement) {
 return this.sqlSessionProxy.<E> selectList(statement);
 }
 /**
 * {@inheritDoc}
 */
 public <E> List<E> selectList(String statement, Object parameter) {
 return this.sqlSessionProxy.<E> selectList(statement, parameter);
 }
 /**
 * {@inheritDoc}
 */
 public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
 return this.sqlSessionProxy.<E> selectList(statement, parameter, rowBounds);
 }
 /**
 * {@inheritDoc}
 */
 public void select(String statement, ResultHandler handler) {
 this.sqlSessionProxy.select(statement, handler);
 }
 /**
 * {@inheritDoc}
 */
 public void select(String statement, Object parameter, ResultHandler handler) {
 this.sqlSessionProxy.select(statement, parameter, handler);
 }
 /**
 * {@inheritDoc}
 */
 public void select(String statement, Object parameter, RowBounds rowBounds, ResultHandler handler) {
 this.sqlSessionProxy.select(statement, parameter, rowBounds, handler);
 }
 /**
 * {@inheritDoc}
 */
 public int insert(String statement) {
 return this.sqlSessionProxy.insert(statement);
 }
 /**
 * {@inheritDoc}
 */
 public int insert(String statement, Object parameter) {
 return this.sqlSessionProxy.insert(statement, parameter);
 }
 /**
 * {@inheritDoc}
 */
 public int update(String statement) {
 return this.sqlSessionProxy.update(statement);
 }
 /**
 * {@inheritDoc}
 */
 public int update(String statement, Object parameter) {
 return this.sqlSessionProxy.update(statement, parameter);
 }
 /**
 * {@inheritDoc}
 */
 public int delete(String statement) {
 return this.sqlSessionProxy.delete(statement);
 }
 /**
 * {@inheritDoc}
 */
 public int delete(String statement, Object parameter) {
 return this.sqlSessionProxy.delete(statement, parameter);
 }
 /**
 * {@inheritDoc}
 */
 public <T> T getMapper(Class<T> type) {
 return getConfiguration().getMapper(type, this);
 }
 /**
 * {@inheritDoc}
 */
 public void commit() {
 throw new UnsupportedOperationException("Manual commit is not allowed over a Spring managed SqlSession");
 }
 /**
 * {@inheritDoc}
 */
 public void commit(boolean force) {
 throw new UnsupportedOperationException("Manual commit is not allowed over a Spring managed SqlSession");
 }
 /**
 * {@inheritDoc}
 */
 public void rollback() {
 throw new UnsupportedOperationException("Manual rollback is not allowed over a Spring managed SqlSession");
 }
 /**
 * {@inheritDoc}
 */
 public void rollback(boolean force) {
 throw new UnsupportedOperationException("Manual rollback is not allowed over a Spring managed SqlSession");
 }
 /**
 * {@inheritDoc}
 */
 public void close() {
 throw new UnsupportedOperationException("Manual close is not allowed over a Spring managed SqlSession");
 }
 /**
 * {@inheritDoc}
 */
 public void clearCache() {
 this.sqlSessionProxy.clearCache();
 }
 /**
 * {@inheritDoc}
 */
 public Connection getConnection() {
 return this.sqlSessionProxy.getConnection();
 }
 /**
 * {@inheritDoc}
 * @since 1.0.2
 */
 public List<BatchResult> flushStatements() {
 return this.sqlSessionProxy.flushStatements();
 }
 /**
 * Proxy needed to route MyBatis method calls to the proper SqlSession got from Spring's Transaction Manager It also
 * unwraps exceptions thrown by {@code Method#invoke(Object, Object...)} to pass a {@code PersistenceException} to
 * the {@code PersistenceExceptionTranslator}.
 */
 private class SqlSessionInterceptor implements InvocationHandler {
 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
 final SqlSession sqlSession = getSqlSession(
  DynamicSqlSessionTemplate.this.getSqlSessionFactory(),
  DynamicSqlSessionTemplate.this.executorType, 
  DynamicSqlSessionTemplate.this.exceptionTranslator);
 try {
 Object result = method.invoke(sqlSession, args);
 if (!isSqlSessionTransactional(sqlSession, DynamicSqlSessionTemplate.this.getSqlSessionFactory())) {
  // force commit even on non-dirty sessions because some databases require
  // a commit/rollback before calling close()
  sqlSession.commit(true);
 }
 return result;
 } catch (Throwable t) {
 Throwable unwrapped = unwrapThrowable(t);
 if (DynamicSqlSessionTemplate.this.exceptionTranslator != null && unwrapped instanceof PersistenceException) {
  Throwable translated = DynamicSqlSessionTemplate.this.exceptionTranslator
  .translateExceptionIfPossible((PersistenceException) unwrapped);
  if (translated != null) {
  unwrapped = translated;
  }
 }
 throw unwrapped;
 } finally {
 closeSqlSession(sqlSession, DynamicSqlSessionTemplate.this.getSqlSessionFactory());
 }
 }
 }
}

SqlSessionContentHolder類代碼如下:

package com.sincetimes.slg.framework.util;
public abstract class SqlSessionContentHolder {
 public final static String SESSION_FACTORY_MASTER = "master";
 public final static String SESSION_FACTORY_SLAVE = "slave";
 private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>(); 
 public static void setContextType(String contextType) { 
 contextHolder.set(contextType); 
 } 
 public static String getContextType() { 
 return contextHolder.get(); 
 } 
 public static void clearContextType() { 
 contextHolder.remove(); 
 } 
}

最后就是寫切面去對dao所有方法進(jìn)行處理了,代碼很簡單如下:

package com.sincetimes.slg.framework.core;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import com.sincetimes.slg.framework.util.SqlSessionContentHolder;
@Aspect
public class DynamicDataSourceAspect {
 @Pointcut("execution( * com.sincetimes.slg.dao.*.*(..))")
 public void pointCut(){
 }
 @Before("pointCut()")
 public void before(JoinPoint jp){
 String methodName = jp.getSignature().getName(); 
 //dao方法查詢走從庫
 if(methodName.startsWith("query") || methodName.startsWith("get") || methodName.startsWith("count") || methodName.startsWith("list")){
 SqlSessionContentHolder.setContextType(SqlSessionContentHolder.SESSION_FACTORY_SLAVE);
 }else{
 SqlSessionContentHolder.setContextType(SqlSessionContentHolder.SESSION_FACTORY_MASTER);
 }
 }
}

以上所述是小編給大家介紹的Spring + Mybatis 項目實現(xiàn)動態(tài)切換數(shù)據(jù)源實例詳解,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!

相關(guān)文章

  • Java中的Pair詳細(xì)

    Java中的Pair詳細(xì)

    這篇文章主要介紹Java中的很有意思的Pair,下面文章會以Pair用法展開,感興趣的小伙伴可以參考下面文章的具體內(nèi)容
    2021-10-10
  • 什么是Java布隆過濾器?如何使用你知道嗎

    什么是Java布隆過濾器?如何使用你知道嗎

    這篇文章主要為大家詳細(xì)介紹了Java布隆過濾器,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助
    2022-02-02
  • SpringBoot+WebSocket+Netty實現(xiàn)消息推送的示例代碼

    SpringBoot+WebSocket+Netty實現(xiàn)消息推送的示例代碼

    這篇文章主要介紹了SpringBoot+WebSocket+Netty實現(xiàn)消息推送的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-04-04
  • Java中的InputStreamReader和OutputStreamWriter源碼分析_動力節(jié)點Java學(xué)院整理

    Java中的InputStreamReader和OutputStreamWriter源碼分析_動力節(jié)點Java學(xué)院整理

    本文通過示例代碼給大家解析了Java中的InputStreamReader和OutputStreamWriter知識,需要的的朋友參考下吧
    2017-05-05
  • Java 的可變參數(shù)方法詳述

    Java 的可變參數(shù)方法詳述

    這篇文章主要介紹了Java 的可變參數(shù)方法,可變參數(shù)只能作為函數(shù)的最后一個參數(shù),在其前面可以有也可以沒有任何其他參數(shù),由于可變參數(shù)必須是最后一個參數(shù),所以一個函數(shù)最多只能有一個可變參數(shù),下面我們一起進(jìn)入文章了解更多關(guān)于可變參數(shù)的內(nèi)容吧
    2022-02-02
  • java 排序算法之選擇排序

    java 排序算法之選擇排序

    本文主要講解了java 排序算法之選擇排序,選擇排序是最簡單直觀的一種算法,想要了解相關(guān)知識的朋友快來看一看這篇文章吧
    2021-09-09
  • 詳解Java中synchronized關(guān)鍵字的死鎖和內(nèi)存占用問題

    詳解Java中synchronized關(guān)鍵字的死鎖和內(nèi)存占用問題

    Java的synchronized關(guān)鍵字用來進(jìn)行線程同步操作,然而這在使用中經(jīng)常會遇到一些問題,這里我們就來詳解Java中synchronized關(guān)鍵字的死鎖和內(nèi)存占用問題:
    2016-06-06
  • SpringBoot做junit測試的時候獲取不到bean的解決

    SpringBoot做junit測試的時候獲取不到bean的解決

    這篇文章主要介紹了SpringBoot做junit測試的時候獲取不到bean的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-09-09
  • Java8如何將Array轉(zhuǎn)換為Stream的實現(xiàn)代碼

    Java8如何將Array轉(zhuǎn)換為Stream的實現(xiàn)代碼

    這篇文章主要介紹了Java8如何將Array轉(zhuǎn)換為Stream的實現(xiàn)代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-09-09
  • EVCache緩存在Spring Boot中的實戰(zhàn)示例

    EVCache緩存在Spring Boot中的實戰(zhàn)示例

    這篇文章主要介紹了EVCache緩存在Spring Boot中的實戰(zhàn)示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-12-12

最新評論