PS:該篇內(nèi)容基于 mybatis 3.4.4 版本 趟妥, 數(shù)據(jù)庫(kù)基于 mysql 5.6
Executor 類圖
主要分析 SimpleExecutor , ReuseExecutor , BatchExecutor , CachingExecutor 的不同點(diǎn)朽基,以及實(shí)際使用中該如何選擇疯搅。
BaseExecutor
BaseExecutor 主要是使用了模板設(shè)計(jì)模式(template), 共性被封裝在 BaseExecutor 中 , 容易變化的內(nèi)容被分離到了子類中 。
SimpleExecutor
MyBatis 的官方文檔中對(duì) SimpleExecutor 的說(shuō)明是 "普通的執(zhí)行器" , 普通就在于每一次執(zhí)行都會(huì)創(chuàng)建一個(gè)新的 Statement 對(duì)象 。下面看一下 mybatis 創(chuàng)建 Statement 對(duì)象的代碼 :
// BaseStatementHandler 中的方法
@Override
public Statement prepare(Connection connection, Integer transactionTimeout) throws SQLException {
ErrorContext.instance().sql(boundSql.getSql());
Statement statement = null;
try {
statement = instantiateStatement(connection);
setStatementTimeout(statement, transactionTimeout);
setFetchSize(statement);
return statement;
} catch (SQLException e) {
closeStatement(statement);
throw e;
} catch (Exception e) {
closeStatement(statement);
throw new ExecutorException("Error preparing statement. Cause: " + e, e);
}
}
// PreparedStatementHandler 中的方法
@Override
protected Statement instantiateStatement(Connection connection) throws SQLException {
String sql = boundSql.getSql();
if (mappedStatement.getKeyGenerator() instanceof Jdbc3KeyGenerator) {
String[] keyColumnNames = mappedStatement.getKeyColumns();
if (keyColumnNames == null) {
return connection.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
} else {
return connection.prepareStatement(sql, keyColumnNames);
}
} else if (mappedStatement.getResultSetType() != null) {
return connection.prepareStatement(sql, mappedStatement.getResultSetType().getValue(), ResultSet.CONCUR_READ_ONLY);
} else {
return connection.prepareStatement(sql);
}
}
在眼見為實(shí)了 mybatis 創(chuàng)建 Statement 對(duì)象的代碼后我們可以看SimpleExecutor 的代碼 , 每次調(diào)用時(shí)都創(chuàng)建了一個(gè)新的 Statement 對(duì)象:
// 實(shí)現(xiàn) BaseExecutor 中的抽象方法
@Override
public <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
Statement stmt = null;
try {
Configuration configuration = ms.getConfiguration();
StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
stmt = prepareStatement(handler, ms.getStatementLog());
return handler.<E>query(stmt, resultHandler);
} finally {
closeStatement(stmt);
}
}
// 獲取一個(gè) Statement , 這里的 handler 默認(rèn)使用的是
// org.apache.ibatis.executor.statement.PreparedStatementHandler
private Statement prepareStatement(StatementHandler handler, Log statementLog) throws SQLException {
Statement stmt;
Connection connection = getConnection(statementLog);
stmt = handler.prepare(connection, transaction.getTimeout());
handler.parameterize(stmt);
return stmt;
}
ReuseExecutor
官方文檔中的解釋是“執(zhí)行器會(huì)重用預(yù)處理語(yǔ)句(prepared statements)” 涛救, 這次倒是解釋的很詳細(xì)。也就是說(shuō)不會(huì)每一次調(diào)用都去創(chuàng)建一個(gè) Statement 對(duì)象 业扒, 而是會(huì)重復(fù)利用以前創(chuàng)建好的(如果SQL相同的話)检吆,這也就是在很多數(shù)據(jù)連接池庫(kù)中常見的 PSCache 概念 。但是ReuseExecutor的PSCache 范圍只能存在于一次回話中 程储, 因?yàn)槊恳淮位卦拑?nèi)部都會(huì)使用一個(gè)新的 ReuseExecutor 對(duì)象 蹭沛, 所以 mybatis 的 PSCache 作用十分有限。
// 存儲(chǔ) SQL 語(yǔ)句對(duì)應(yīng)的 Statement 對(duì)象
private final Map<String, Statement> statementMap = new HashMap<String, Statement>();
// .....
private Statement prepareStatement(StatementHandler handler, Log statementLog) throws SQLException {
Statement stmt;
BoundSql boundSql = handler.getBoundSql();
String sql = boundSql.getSql();
// 檢查該 sql 是否有可用的 Statement 章鲤, 如果有的話直接從緩存中獲取 摊灭, 沒有的話創(chuàng)建新的 Statement 并緩存
if (hasStatementFor(sql)) {
stmt = getStatement(sql);
applyTransactionTimeout(stmt);
} else {
Connection connection = getConnection(statementLog);
stmt = handler.prepare(connection, transaction.getTimeout());
putStatement(sql, stmt);
}
handler.parameterize(stmt);
return stmt;
}
SimpleExecutor & ReuseExecutor 對(duì)比總結(jié)
SimpleExecutor 比 ReuseExecutor 的性能要差 , 因?yàn)?SimpleExecutor 沒有做 PSCache败徊。為什么做了 PSCache 性能就會(huì)高呢 帚呼, 因?yàn)楫?dāng)SQL越復(fù)雜占位符越多的時(shí)候預(yù)編譯的時(shí)間也就越長(zhǎng),創(chuàng)建一個(gè) PreparedStatement 對(duì)象的時(shí)間也就越長(zhǎng)皱蹦。測(cè)試代碼 :
public class PrepareStatementTest {
private static final Logger LOG = LoggerFactory.getLogger(PrepareStatementTest.class);
private static final Properties PROP = new Properties();
private static final int COUNT = 2000000;
private String driverClass;
private String url;
private String user;
private String password;
private static final StringBuilder TEST_PREPAREED_STATEMENT_SQL = new StringBuilder();
private long startTime;
@Before
public void init() throws Exception {
PROP.load(PrepareStatementTest.class.getClassLoader().getResourceAsStream("jdbc.properties"));
this.driverClass = PROP.getProperty("jdbc.driver");
this.url = PROP.getProperty("jdbc.url");
this.user = PROP.getProperty("jdbc.user");
this.password = PROP.getProperty("jdbc.password");
DriverManager.registerDriver((Driver) Class.forName(this.driverClass).newInstance());
TEST_PREPAREED_STATEMENT_SQL.append("INSERT INTO `user` (nickname,realname,phone,login_password,pay_password,create_time,update_time) VALUES");
for (int i = 0 ; i < COUNT ; i++ ) {
if (i == COUNT - 1) {
TEST_PREPAREED_STATEMENT_SQL.append(" (?,?,?,?,?,?,?)");
} else {
TEST_PREPAREED_STATEMENT_SQL.append(" (?,?,?,?,?,?,?)").append(", ");
}
}
this.startTime = System.currentTimeMillis();
}
@After
public void after() throws Exception {
LOG.debug("======> cost time {} ms" , (System.currentTimeMillis() - this.startTime));
}
@Test
public void costTime() throws Exception {
Connection connection = DriverManager.getConnection(url, user, password);
PreparedStatement ps = connection.prepareStatement(TEST_PREPAREED_STATEMENT_SQL.toString());
}
}
BatchExecutor
BatchExecutor 的特性其實(shí)非常簡(jiǎn)單煤杀,其實(shí)就是調(diào)用了 Statement 的 addBatch 方法。另外千萬(wàn)不要認(rèn)為 BatchExecutor 比 ReuseExecutor 功能強(qiáng)大性能高 沪哺, 實(shí)際上不是的 BatchExecutor 是沒有做 PSCache 的怜珍。
@Override
public int doUpdate(MappedStatement ms, Object parameterObject) throws SQLException {
final Configuration configuration = ms.getConfiguration();
final StatementHandler handler = configuration.newStatementHandler(this, ms, parameterObject, RowBounds.DEFAULT, null, null);
final BoundSql boundSql = handler.getBoundSql();
final String sql = boundSql.getSql();
final Statement stmt;
if (sql.equals(currentSql) && ms.equals(currentStatement)) {
int last = statementList.size() - 1;
stmt = statementList.get(last);
applyTransactionTimeout(stmt);
handler.parameterize(stmt);//fix Issues 322
BatchResult batchResult = batchResultList.get(last);
batchResult.addParameterObject(parameterObject);
} else {
Connection connection = getConnection(ms.getStatementLog());
stmt = handler.prepare(connection, transaction.getTimeout());
handler.parameterize(stmt); //fix Issues 322
currentSql = sql;
currentStatement = ms;
statementList.add(stmt);
batchResultList.add(new BatchResult(ms, sql, parameterObject));
}
// handler.parameterize(stmt);
handler.batch(stmt);
return BATCH_UPDATE_RETURN_VALUE;
}
BatchExecutor 與 SimpleExecutor 和 ReuseExecutor 還有一個(gè)區(qū)別就是 , BatchExecutor 的事務(wù)是沒法自動(dòng)提交的凤粗。因?yàn)?BatchExecutor 只有在調(diào)用了 SqlSession 的 commit 方法的時(shí)候 , 它才會(huì)去執(zhí)行 executeBatch 方法。
// BaseExecutor 的 commit 方法
public void commit(boolean required) throws SQLException {
if (closed) throw new ExecutorException("Cannot commit, transaction is already closed");
clearLocalCache();
flushStatements();
if (required) {
transaction.commit();
}
}
// BatchExecutor 中的 doFlushStatements 方法
@Override
public List<BatchResult> doFlushStatements(boolean isRollback) throws SQLException {
try {
List<BatchResult> results = new ArrayList<BatchResult>();
if (isRollback) {
return Collections.emptyList();
}
for (int i = 0, n = statementList.size(); i < n; i++) {
Statement stmt = statementList.get(i);
applyTransactionTimeout(stmt);
BatchResult batchResult = batchResultList.get(i);
try {
// 這里才調(diào)用了 executeBatch 方法
batchResult.setUpdateCounts(stmt.executeBatch());
MappedStatement ms = batchResult.getMappedStatement();
List<Object> parameterObjects = batchResult.getParameterObjects();
KeyGenerator keyGenerator = ms.getKeyGenerator();
if (Jdbc3KeyGenerator.class.equals(keyGenerator.getClass())) {
Jdbc3KeyGenerator jdbc3KeyGenerator = (Jdbc3KeyGenerator) keyGenerator;
jdbc3KeyGenerator.processBatch(ms, stmt, parameterObjects);
} else if (!NoKeyGenerator.class.equals(keyGenerator.getClass())) { //issue #141
for (Object parameter : parameterObjects) {
keyGenerator.processAfter(this, ms, stmt, parameter);
}
}
} catch (BatchUpdateException e) {
StringBuilder message = new StringBuilder();
message.append(batchResult.getMappedStatement().getId())
.append(" (batch index #")
.append(i + 1)
.append(")")
.append(" failed.");
if (i > 0) {
message.append(" ")
.append(i)
.append(" prior sub executor(s) completed successfully, but will be rolled back.");
}
throw new BatchExecutorException(message.toString(), e, results, batchResult);
}
results.add(batchResult);
}
return results;
} finally {
for (Statement stmt : statementList) {
closeStatement(stmt);
}
currentSql = null;
statementList.clear();
batchResultList.clear();
}
}
CachingExecutor
再回頭去看一下 Executor 組件的類結(jié)構(gòu)圖 嫌拣, 發(fā)現(xiàn) CachingExecutor 沒有 extends BaseExecutor 柔袁, 為什么?一定有原因這個(gè)世界上沒有無(wú)緣無(wú)故的事情异逐〈匪鳎看看 CachingExecutor 的實(shí)現(xiàn),發(fā)現(xiàn) CachingExecutor 其實(shí)是一個(gè)裝飾者對(duì)象 灰瞻, mybatis 這里對(duì) Executor 的設(shè)計(jì)使用了 Decorator (裝飾者) 設(shè)計(jì)模式腥例。
public class CachingExecutor implements Executor {
private Executor delegate;
private TransactionalCacheManager tcm = new TransactionalCacheManager();
public CachingExecutor(Executor delegate) {
this.delegate = delegate;
delegate.setExecutorWrapper(this);
}
接下來(lái)說(shuō)明 CachingExecutor 這個(gè)裝飾者對(duì)象的作用 ,看名字的話也能猜的差不多了 酝润, 這個(gè)裝飾對(duì)象是用來(lái)處理二級(jí)緩存的燎竖。 當(dāng)全局設(shè)置開啟了二級(jí)緩存時(shí)會(huì)初始化一個(gè) CachingExecutor 。
// org.apache.ibatis.session.Configuration 中的方法
public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
executorType = executorType == null ? defaultExecutorType : executorType;
executorType = executorType == null ? ExecutorType.SIMPLE : executorType;
Executor executor;
if (ExecutorType.BATCH == executorType) {
executor = new BatchExecutor(this, transaction);
} else if (ExecutorType.REUSE == executorType) {
executor = new ReuseExecutor(this, transaction);
} else {
executor = new SimpleExecutor(this, transaction);
}
// 如果開啟了二級(jí)緩存 要销, 實(shí)例化 CachingExecutor 對(duì)象
if (cacheEnabled) {
executor = new CachingExecutor(executor);
}
executor = (Executor) interceptorChain.pluginAll(executor);
return executor;
}
// CachingExecutor
@Override
public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql)
throws SQLException {
Cache cache = ms.getCache();
if (cache != null) {
flushCacheIfRequired(ms);
if (ms.isUseCache() && resultHandler == null) {
ensureNoOutParams(ms, parameterObject, boundSql);
@SuppressWarnings("unchecked")
List<E> list = (List<E>) tcm.getObject(cache, key);
if (list == null) {
list = delegate.<E> query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
tcm.putObject(cache, key, list); // issue #578 and #116
}
return list;
}
}
return delegate.<E> query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
}
總結(jié)
實(shí)際生產(chǎn)環(huán)境中建議使用 ReuseExecutor 构回, 另外在實(shí)際應(yīng)用中涉及到大量數(shù)據(jù)的更新,插入操作不建議使用 mybatis 而應(yīng)該使用原生的 JDBC 操作 疏咐, 因?yàn)閿?shù)據(jù)量很大的時(shí)候進(jìn)行一次 executeBatch 也是很耗時(shí)的 纤掸, 使用原生 JDBC 操作可以 clearBatch 和 executeBatch 結(jié)合使用提高性能 ; 通過對(duì)源碼的分析,了解到了各個(gè)Executor實(shí)現(xiàn)的優(yōu)劣 浑塞, 它們之間的組織與協(xié)同關(guān)系 借跪, 希望閱讀源碼不僅僅是熟悉了框架的運(yùn)行流程,實(shí)現(xiàn)原理酌壕,更能體會(huì)作者的思想掏愁,分析出框架的優(yōu)點(diǎn)缺點(diǎn) , 結(jié)合實(shí)際為自己所用仅孩。站在巨人的肩膀上能看的更遠(yuǎn)托猩。