MyBatis的設計思想很簡單,能夠看作是對JDBC的一次封裝,並提供強大的動態SQL映射功能。可是因爲它自己也有一些緩存、事務管理等功能,因此實際使用中仍是會碰到一些問題——另外,最近接觸了JFinal,其思想和Hibernate相似,但要更簡潔,和MyBatis的設計思想不一樣,但有一點相同:都是想經過簡潔的設計最大限度地簡化開發和提高性能——說到性能,前段時間碰到兩個問題:java
第一個問題是偶爾會出現,在實驗環境不管如何也重現不了,通過分析MyBatis的邏輯,估計是兩個DAO分別拿到了兩個不一樣的Connection,第二個語句比第一個更早的被提交,致使了主鍵衝突,有待進一步的分析和驗證。對於第二個問題,本文將嘗試經過分析源代碼和實驗找到它的root cause,主要涉及到如下內容:mysql
整個系統是微服務架構,這裏討論的「項目」是指一個單獨的服務。單個項目的框架基本是Spring+MyBatis,具體版本以下:spring
Spring 3.2.9/4.3.5 + Mybatis 3.2.6 + mybatis-spring 1.2.2 + mysql connector 5.1.20 + commons-dbcp 1.4
與MyBatis和事務相關的配置以下:sql
//代碼1 <!-- bean#1--> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <!-- 一些數據庫信息配置--> <!-- 一些DBCP鏈接池配置 --> //在這裏設置是否自動提交 <property name="defaultAutoCommit" value="${dbcp.defaultAutoCommit}" /> </bean> <!-- bean#2--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="mapperLocations" value="classpath*:path/to/mapper/**/*.xml" /> </bean> <!-- bean#3 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- bean#4--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value=".path.to.mapper" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> </bean> <!-- bean5 --> <tx:annotation-driven transaction-manager="transactionManager" />
一倍的時間差挺嚴重的,平均到每次調用,正常的大約在6到10幾 ms
,慢的要近20 ms
,因爲調用次數不少,致使總體性能會有很大的差異。通過仔細比對這幾個項目,發現DAO執行慢的項目的數據源配置(bean#1)中 defaultAutoCommit
的配置都是 false
。並且將此配置改成 true
以後就恢復了正常。 數據庫
由此推斷是在MyBatis在執行「非自動提交」語句時,進行等待,或者多提交了一次,致使實際調用數據庫API次數增多。可是這個推斷也有個問題,因爲整個項目是在Spring環境中運行的,並且也開啓了Spring的事務管理,因此仍是須要詳細的看一下MyBatis究竟是如何裝配DAO方法與管理事務的,才能完全解開謎團。apache
首先寫一個Service,其中調用了同一個mapper類的兩個方法分別2次, insertModelList()
會在數據庫中插入兩條記錄, delModels()
方法會刪除這兩條記錄,代碼以下:緩存
//代碼2 //@Transactional public void testIS(){ List<Model> models= new ArrayList<>(); //省略一些數據工做。。。 modelMapper.insertModelList(50001l, models); modelMapper.delModels(50001); if (CollectionUtils.isNotEmpty(models)) modelMapper.insertModelList(50001, models); modelMapper.delModels(50001); } public void testOther(){ System.out.println("加載類:"); System.out.println(modelMapper.getClass().getClassLoader()); modelMapper.delModels(50001); }
實際項目中使用cat來進行執行時間的統計,這裏也仿照cat,使用一個單獨的AOP類實現時間的計算:session
//代碼3 public class DaoTimeAdvice { private long time = 0; private long num = 0; public Object calcTime(ProceedingJoinPoint joinPoint) throws Throwable { long then = System.nanoTime(); Object object = joinPoint.proceed(); long now = System.nanoTime(); setTime(getTime() + (now-then)); setNum(getNum() + 1); return object; } //省略getter & setter。。。 public void printInfo() { System.out.println("總共次數:" + num); System.out.println("總共時間:" + time); System.out.println("平均時間:" + time / num); } }
測試代碼:mybatis
//代碼4 public static void test(){ System.out.println(new SimpleDateFormat("[yyyy-MM-dd HH:mm:ss]").format(new Date()) + " 開始測試!"); for (int i = 0; i < TEST_NUM; i++) { ItemStrategyServiceTest ist = (ItemStrategyServiceTest) context.getBean("isTS"); ist.testIS(); if (i % 1000 == 0) { System.out.println("1000次"); } } DaoTimeAdvice ad = (DaoTimeAdvice) context.getBean("daoTimeAdvice"); ad.printInfo(); ItemStrategyServiceTest ist = (ItemStrategyServiceTest) context.getBean("isTS"); ist.testOther(); System.exit(1); }
測試結果:架構
defaultAutoCommit |
循環次數 | 共消耗時間(ns) | 平均時間(ns) |
---|---|---|---|
true | 40000 | 17831088316 | 445777 |
true | 40000 | 17881589992 | 447039 |
false | 40000 | 27280458229 | 682011 |
false | 40000 | 27237413893 | 680935 |
defaultAutoCommit爲 false
時的執行時間是 true
的近1.5倍,並無重現2倍的時間消耗,估計是在cat統計或者其餘AOP方法的執行時還有其餘消耗,從而擴大了 false
和 true
之間的區別。
按照第一節中的配置文件,整個MyBatis中DAO的bean的裝配應該是這樣的:
dataSource
。 這個bean很簡單,就是實例化並註冊到Spring的上下文中。
dataSource
來建立 sqlSessionFactory
(bean#2),這個bean建立時會掃描MyBatis的語句映射文件並解析。 在MyBatis中,真正的數據庫讀寫操做是經過SqlSession的實例來實現的,而SqlSession要經過SQLSessionFactory來管理。這裏的 org.mybatis.spring.SqlSessionFactoryBean
實現了FactoryBean類(這個類比較特殊,與主題無關,這裏再也不贅述),Spring會從這個bean中會獲取真正的SQLSessionFactory的實例,源代碼中顯示,實際返回的對象是DefaultSqlSessionFactory的實例。
使用 sqlSessionFactory
這個工廠類來建立mapper掃描器(bean#4),並建立含有DAO方法的實例。
爲了讓上層方法能夠經過普通的方法調用來使用DAO方法,須要往Spring上下文裏註冊相應的bean,而在MyBatis的普通使用場景中是沒有mapper的實現類的(具體的SQL語句映射經過註解或者XML文件來實現),只有接口,在MyBatis中這些接口是經過動態代理實現的。這裏使用的類是 org.mybatis.spring.mapper.MapperScannerConfigurer
,它實現了 org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor
接口,因此會在Spring中「全部的bean定義所有註冊完成,但尚未實例化」以前,調用方法向Spring上下文註冊mapper實現類(動態代理的對象)。具體代碼以下:
//代碼5 @Override public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) { if (this.processPropertyPlaceHolders) { processPropertyPlaceHolders(); } ClassPathMapperScanner scanner = new ClassPathMapperScanner(registry); //設置一些屬性 scanner.scan(StringUtils.tokenizeToStringArray(this.basePackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS)); } /** * Perform a scan within the specified base packages. * @param basePackages the packages to check for annotated classes
*/
public int scan(String... basePackages) { int beanCountAtScanStart = this.registry.getBeanDefinitionCount(); doScan(basePackages); // Register annotation config processors, if necessary. if (this.includeAnnotationConfig) { AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry); } return (this.registry.getBeanDefinitionCount() - beanCountAtScanStart); }
在源代碼裏能夠看到,真正的mapper實現類是 ` org.mybatis.spring.mapper.MapperFactoryBean<Object>`,具體的邏輯在方法 ` org.mybatis.spring.mapper.ClassPathMapperScanner.processBeanDefinitions(Set<BeanDefinitionHolder>)`裏。最後,每個方法的執行,最終落入了 ` org.mybatis.spring.SqlSessionTemplate`的某個方法中,並被以下這個攔截器攔截:
//代碼6 /** * 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 { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { SqlSession sqlSession = getSqlSession( SqlSessionTemplate.this.sqlSessionFactory, SqlSessionTemplate.this.executorType, SqlSessionTemplate.this.exceptionTranslator); try { Object result = method.invoke(sqlSession, args); if (!isSqlSessionTransactional(sqlSession, SqlSessionTemplate.this.sqlSessionFactory)) { // 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) { //省略一些錯誤處理 throw unwrapped; } finally { if (sqlSession != null) { closeSqlSession(sqlSession, SqlSessionTemplate.this.sqlSessionFactory); } } } }
4. MyBatis在Spring環境下事務的管理 從源代碼中知道真正的SqlSessionFactory使用的是 ` org.apache.ibatis.session.defaults.DefaultSqlSessionFactory`的實例,同時,事務管理使用 ` org.mybatis.spring.transaction.SpringManagedTransactionFactory`。可是在代碼1的配置中,還添加了Spring事務管理的配置,就是在某個Service方法(或某個其餘可被掃描到的方法)上加上 ` @Transactional`註解,那麼Spring的事務管理會自動建立事務,那麼它和MyBatis的事務之間是怎麼協做的呢? 能夠看到在代碼6中的方法 ` isSqlSessionTransactional()`,它會返回上層代碼中是否有Spring的事務,若是有,將不會執行下邊的 ` commit()`。在個人項目中的實際狀況是沒有Spring事務,因此確定是走到了下面的 ` commit()`,這個方法最終落到了 ` SpringManagedTransactionFactory`中的 ` commit()`,看代碼:
//代碼7 private void openConnection() throws SQLException { this.connection = DataSourceUtils.getConnection(this.dataSource); this.autoCommit = this.connection.getAutoCommit(); this.isConnectionTransactional = DataSourceUtils.isConnectionTransactional(this.connection, this.dataSource); } public void commit() throws SQLException { if (this.connection != null && !this.isConnectionTransactional && !this.autoCommit) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Committing JDBC Connection [" + this.connection + "]"); } this.connection.commit(); } }
能夠看到,此處是否要執行 ` commit()`操做是由3個變量決定的,若是DataSource的 ` autoCommit`是 ` false`,則其結果必定爲 ` true`,控制檯也會看到一行日誌: ` Committing JDBC Connection [xxxxxx]`,恰好與項目中遇到的狀況相同。這個提交動做是須要和數據庫交互的,比較耗時。 ### 實驗驗證 由上一節分析得出,形成DAO方法執行時間變長的緣由是會多執行一次提交,那麼若是上層方法被Spring事務管理器託管(或者數據源的 ` defaultAutoCommit`爲 ` true`,這個條件已經在剛開始的問題重現被驗證),則不會執行MyBatis的提交動做,DAO方法應該相應的執行時間會變短。因而將Service方法加上 ` @transactional`註解,分別測試 ` true`和 ` false`的狀況。結果: 