前言
本文讨论的源码是基于connectorJ 5.1.37,最新版的jar包是5.1.38,两者对于该处的逻辑并无差别。
connectorJ mysql官网下载地址:点击打开链接(http://dev.mysql.com/downloads/connector/j/)
一、JDBC API支持
java.sql.Statement中定义的查询超时规范:
/**
* Sets the number of seconds the driver will wait for a
* <code>Statement</code> object to execute to the given number of seconds.
*By default there is no limit on the amount of time allowed for a running
* statement to complete. If the limit is exceeded, an
* <code>SQLTimeoutException</code> is thrown.
* A JDBC driver must apply this limit to the <code>execute</code>,
* <code>executeQuery</code> and <code>executeUpdate</code> methods.
* <p>
* <strong>Note:</strong> JDBC driver implementations may also apply this
* limit to {@code ResultSet} methods
* (consult your driver vendor documentation for details).
* <p>
* <strong>Note:</strong> In the case of {@code Statement} batching, it is
* implementation defined as to whether the time-out is applied to
* individual SQL commands added via the {@code addBatch} method or to
* the entire batch of SQL commands invoked by the {@code executeBatch}
* method (consult your driver vendor documentation for details).
*
* @param seconds the new query timeout limit in seconds; zero means
* there is no limit
* @exception SQLException if a database access error occurs,
* this method is called on a closed <code>Statement</code>
* or the condition {@code seconds >= 0} is not satisfied
* @see #getQueryTimeout
*/
void setQueryTimeout(int seconds) throws SQLException;
JDBC规范中的执行对象关系——CallableStatement extends PreparedStatement extends Statement,因此setQueryTimeout均可以支持。
二、JDBC实现源码浅析
三、Mysql对超时的支持
整个JDBC规范及其实现中,将java与mysql联系到一起的是connection对象,实际上jdbc操作也是一种RPC,java应用远程调用mysql应用,通过jdbc协议进行通信。而JDBC协议(jdbc:mysql://xxxx/3306/database,主协议是jdbc,副协议是mysql)基于socket,在connection.connect(url, properties)的逻辑中通过反射connection实现类的构造函数实例化MysqlIO对象,此时会进行socket通信和握手协议,失败则JDBC异常。
扯远了,回到Mysql对超时的技术支持。
参见mysql官方文档中关于kill query的内容:13.7.6.3 KILL Syntax
对应的中文翻译:点击打开链接
其中关注两个点,指令语法和指令含义。
1. 语法
KILL [CONNECTION | QUERY] thread_id
2. 含义
KILL QUERY terminates the statement the connection is currently executing, but leaves the connection itself intact.
KILL QUERY会终止连接当前正在执行的语句,但是会保持连接的原状。
3. 注意
需要注意的是,KILL QUERY指令并不会关闭当前连接,而只是结束当前连接的操作,否则连接池在超时机制下就没什意义了。
四、测试demo
再次重复一下,kill query thread_id超时杀操作是不会导致连接对象关闭的,测试demo及执行结果如下。
五、总结
JDBC中查询超时的逻辑:
1. 在进行查询操作的时候启动定时器,超时则调用CancelTask;
2. 在CancelTask中,java应用通过jdbc协议对mysql服务器进行RPC,调用mysql “KILL QUERY”指令结束当前连接执行的操作;
3. 如果在执行完query操作还没有超时,则取消CancelTask,否则CancelTask在超时后RPC “KILL QUERY";
附注:
本文写的过于简单,乘中午休息时间不睡觉匆忙写了写,有些地方不详细,如有错漏,还请不吝指正,谢谢!