JDBC query timeout setting

    We sometimes need to control the maximum time-consuming of SQL queries. For example, if a "execution time" SQL is not executed within a specified time, we need to "cancel" the SQL. We know that in JDBC, the Statement class can pass setQueryTimeout() to implement this feature.

    When the query timeout is set, the JDBC client sends the request and waits until the execution is completed or times out. After the timeout, the client tries to cancel the current SQL and asks the mysql server to interrupt the execution. Because the network communication takes time, it may be when the client tries to cancel. , the mysql server has been executed successfully, and the request will be returned (rather than canceled); if the cancellation is successful after the timeout, the current client call will throw a SQLTimeoutException.

 

    The queryTimeout option cannot be passed in as properties in the JDBC Url at present, so it cannot be specified in the URL like the socketTimeout and connectionTimeout parameters.

 

1. Mybatis sets timeout

    1. Set in mybatis-config.xml: The settings here are valid for all sql globally, including insert, select, update, etc.

 

<settings>
	<setting name="defaultStatementTimeout" value="25"/>
        <!-- Unit: seconds -->
</settings>

 

 

    2. Set in the statement statement: only valid for the current statement. There are timeout attributes in select, insert, update and other statements

 

<select
  id="selectPerson"
  timeout="10000" ...>

 

 

2. Settings in JPA

    1. Set the timeout for the current query:

String sql = "SELECT ...";
TypedQuery<User> query = entityManager.createQuery(sql, User.class);
query.setParameter("id", id);
//Set timeout here, unit: milliseconds
query.setHint("javax.persistence.query.timeout", 20000);

 

    2. JPA global configuration

<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>

 

3. JNDI mode configuration

    Usually, our online database datasource management is based on JNDI. Of course, we can manage this option in JNDI. This article is based on tomcat-pool:

<Resource name="jdbc/masterDB"  jdbcInterceptors="QueryTimeoutInterceptor(queryTimeout=20000)" />
##Unit: seconds, the timeout parameter is not enabled by default

 

    We only need to add a jdbcInterceptors to the Resource configuration. For the specific configuration, see [tomcat-pool]

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326711823&siteId=291194637