我们有时候需要控制SQL查询的最大耗时,比如一个“执行时长”的SQL在指定时间内如果没有执行完毕,我们需要“取消”此SQL,我们知道在JDBC中Statement类可以通过setQueryTimeout()来实现此特性。
当设置query timeout之后,JDBC客户端发送请求,并等待直到执行完成或者超时,当超时后,客户端尝试cancel当前SQL,要求mysql server中断执行,因为网络通讯需要时间,可能在客户端尝试cancel时,mysql server已经执行成功,此时请求将会返回(而不是取消);超时后取消成功,那么当前客户端调用将会抛出SQLTimeoutException。
queryTimeout选项,目前不能在JDBC Url中作为properties传入,所以不能像socketTimeout、connectionTimeout参数那样可以在URL中指定。
一、mybatis设置timeout
1、在mybatis-config.xml中设置:此处设置对全局的所有sql都生效,包括insert、select、update等。
<settings> <setting name="defaultStatementTimeout" value="25"/> <!-- 单位:秒 --> </settings>
2、在statement语句中设置:只对当前statement有效,select、insert、update等语句中都有timeout属性
<select id="selectPerson" timeout="10000" ...>
二、 JPA中设置
1、为当前查询设定timeout:
String sql = "SELECT ..."; TypedQuery<User> query = entityManager.createQuery(sql, User.class); query.setParameter("id", id); //此处设置timeout,单位:毫秒 query.setHint("javax.persistence.query.timeout", 20000);
2、JPA全局配置
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="jpaProperties"> <props> <prop key="eclipselink.cache.shared.default">false</prop> <prop key="eclipselink.weaving">false</prop> <prop key="javax.persistence.query.timeout”>20000<prop/> </props> </property> </bean>
三、JNDI方式配置
通常情况下,我们线上的数据库datasource管理是基于JNDI的方式,当然我们可以在JNDI中管理此选项,本文基于tomcat-pool的方式:
<Resource name="jdbc/masterDB" jdbcInterceptors="QueryTimeoutInterceptor(queryTimeout=20000)" /> ##单位:秒,默认不开启timeout 参数
我们只需要在Resource配置中增加一个jdbcInterceptors即可,具体配置参见【tomcat-pool】