Skip to content

Commit 1282890

Browse files
committed
Add 'defaultNetworkTimeout' to PooledDataSource and UnpooledDataSource
As it calls `java.sql.Connection#setNetworkTimeout()` internally, setting this property requires a driver supporting JDBC 4.1.
1 parent 5745787 commit 1282890

File tree

8 files changed

+107
-6
lines changed

8 files changed

+107
-6
lines changed

src/main/java/org/apache/ibatis/datasource/pooled/PooledDataSource.java

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,18 @@ public void setDriverProperties(Properties driverProps) {
149149
forceCloseAll();
150150
}
151151

152+
/**
153+
* Sets the default network timeout value to wait for the database operation to complete. See {@link Connection#setNetworkTimeout(java.util.concurrent.Executor, int)}
154+
*
155+
* @param milliseconds
156+
* The time in milliseconds to wait for the database operation to complete.
157+
* @since 3.5.2
158+
*/
159+
public void setDefaultNetworkTimeout(Integer milliseconds) {
160+
dataSource.setDefaultNetworkTimeout(milliseconds);
161+
forceCloseAll();
162+
}
163+
152164
/**
153165
* The maximum number of active connections.
154166
*
@@ -263,6 +275,13 @@ public Properties getDriverProperties() {
263275
return dataSource.getDriverProperties();
264276
}
265277

278+
/**
279+
* @since 3.5.2
280+
*/
281+
public Integer getDefaultNetworkTimeout() {
282+
return dataSource.getDefaultNetworkTimeout();
283+
}
284+
266285
public int getPoolMaximumActiveConnections() {
267286
return poolMaximumActiveConnections;
268287
}

src/main/java/org/apache/ibatis/datasource/unpooled/UnpooledDataSource.java

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
import java.util.Map;
2626
import java.util.Properties;
2727
import java.util.concurrent.ConcurrentHashMap;
28+
import java.util.concurrent.Executors;
2829
import java.util.logging.Logger;
2930

3031
import javax.sql.DataSource;
@@ -48,6 +49,7 @@ public class UnpooledDataSource implements DataSource {
4849

4950
private Boolean autoCommit;
5051
private Integer defaultTransactionIsolationLevel;
52+
private Integer defaultNetworkTimeout;
5153

5254
static {
5355
Enumeration<Driver> drivers = DriverManager.getDrivers();
@@ -182,6 +184,24 @@ public void setDefaultTransactionIsolationLevel(Integer defaultTransactionIsolat
182184
this.defaultTransactionIsolationLevel = defaultTransactionIsolationLevel;
183185
}
184186

187+
/**
188+
* @since 3.5.2
189+
*/
190+
public Integer getDefaultNetworkTimeout() {
191+
return defaultNetworkTimeout;
192+
}
193+
194+
/**
195+
* Sets the default network timeout value to wait for the database operation to complete. See {@link Connection#setNetworkTimeout(java.util.concurrent.Executor, int)}
196+
*
197+
* @param milliseconds
198+
* The time in milliseconds to wait for the database operation to complete.
199+
* @since 3.5.2
200+
*/
201+
public void setDefaultNetworkTimeout(Integer defaultNetworkTimeout) {
202+
this.defaultNetworkTimeout = defaultNetworkTimeout;
203+
}
204+
185205
private Connection doGetConnection(String username, String password) throws SQLException {
186206
Properties props = new Properties();
187207
if (driverProperties != null) {
@@ -224,6 +244,9 @@ private synchronized void initializeDriver() throws SQLException {
224244
}
225245

226246
private void configureConnection(Connection conn) throws SQLException {
247+
if (defaultNetworkTimeout != null) {
248+
conn.setNetworkTimeout(Executors.newSingleThreadExecutor(), defaultNetworkTimeout);
249+
}
227250
if (autoCommit != null && autoCommit != conn.getAutoCommit()) {
228251
conn.setAutoCommit(autoCommit);
229252
}

src/site/es/xdoc/configuration.xml

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1627,7 +1627,7 @@ SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader,properti
16271627
</ul>
16281628
<p>Hay tres tipos de dataSources pre-construidos (ej. type=”????”):</p>
16291629
<p>
1630-
<strong>UNPOOLED</strong> – Esta implementación de DataSource abre y cierra una conexión JDBC cada vez que se solcita una conexión. Aunque es un poco lento, es una buena elección para aplicaciones que no necesitan la velocidad de tener conexiones abiertas de forma inmediata. Las bases de datos tienen un rendimiento distinto en cuanto al rendimiento que aportan con este tipo de DataSource, para algunas de ellas no es muy importante tener un pool y por tanto esta configuración es apropiada. El DataSource UNPOOLED tiene cinco opciones de configuración:
1630+
<strong>UNPOOLED</strong> – Esta implementación de DataSource abre y cierra una conexión JDBC cada vez que se solcita una conexión. Aunque es un poco lento, es una buena elección para aplicaciones que no necesitan la velocidad de tener conexiones abiertas de forma inmediata. Las bases de datos tienen un rendimiento distinto en cuanto al rendimiento que aportan con este tipo de DataSource, para algunas de ellas no es muy importante tener un pool y por tanto esta configuración es apropiada. El DataSource UNPOOLED tiene las siguientes opciones de configuración:
16311631
</p>
16321632
<ul>
16331633
<li><code>driver</code> – El nombre completamente cualificado de la clase java del driver JDBC (NO de la clase DataSource en el caso de que tu driver incluya una).</li>
@@ -1639,6 +1639,8 @@ SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader,properti
16391639
</li>
16401640
<li><code>defaultTransactionIsolationLevel</code> – El nivel de aislamiento por defecto con el que se crearán las conexiones.
16411641
</li>
1642+
<li><code>defaultNetworkTimeout</code> – The default network timeout value in milliseconds to wait for the database operation to complete. See the API documentation of <code>java.sql.Connection#setNetworkTimeout()</code> for details.
1643+
</li>
16421644
</ul>
16431645
<p>Opcionalmente, puedes también pasar propiedades al driver de la base de datos. Para ello prefija las propiedades con “driver.”, por ejemplo:
16441646
</p>

src/site/ja/xdoc/configuration.xml

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1717,7 +1717,7 @@ SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader,properti
17171717
少々遅いですが、即時の接続を必要としないシンプルなアプリケーションの場合は良い選択肢です。
17181718
パフォーマンスに関しては、お使いのデータベースによっても変わってきます。
17191719
接続プールの重要性が低いデータベースの場合はこの設定が最適となります。
1720-
UNPOOLED データソースは5つのプロパティで設定できます
1720+
UNPOOLED データソースに対して設定可能なプロパティは下記の通りです
17211721
</p>
17221722
<ul>
17231723
<li>driver – JDBC ドライバーの完全修飾 Java クラス名(ドライバーに含まれているデータソースクラスではありません)
@@ -1730,6 +1730,8 @@ SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader,properti
17301730
</li>
17311731
<li>defaultTransactionIsolationLevel – デフォルトのトランザクション分離レベル
17321732
</li>
1733+
<li>defaultNetworkTimeout – 任意の要求に対するデータベースからの応答待機期限のデフォルト値(ミリ秒)。詳細は <code>java.sql.Connection#setNetworkTimeout()</code> の javadoc 参照。
1734+
</li>
17331735
</ul>
17341736
<p>
17351737
オプションとして、データベースドライバーのプロパティを設定することもできます。

src/site/ko/xdoc/configuration.xml

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1598,13 +1598,15 @@ SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader,properti
15981598
<p>
15991599
<strong>UNPOOLED</strong> - 이 구현체는 매번 요청에 대해 커넥션을 열고 닫는 간단한 DataSource이다.
16001600
조금 늦긴 하지만 성능을 크게 필요로 하지 않는 간단한 애플리케이션을 위해서는 괜찮은 선택이다.
1601-
UNPOOLED DataSource는 5 개의 프로퍼티만으로 설정한다.</p>
1601+
UNPOOLED DataSource에는 다음과 같은 속성이 있습니다.</p>
16021602
<ul>
16031603
<li><code>driver</code> - JDBC드라이버의 패키지 경로를 포함한 결제 자바 클래스명</li>
16041604
<li><code>url</code> - 데이터베이스 인스턴스에 대한 JDBC URL</li>
16051605
<li><code>username</code> - 데이터베이스에 로그인 할 때 사용할 사용자명</li>
16061606
<li><code>password</code> - 데이터베이스에 로그인 할 때 사용할 패스워드</li>
16071607
<li><code>defaultTransactionIsolationLevel</code> - 커넥션에 대한 디폴트 트랜잭션 격리 레벨</li>
1608+
<li><code>defaultNetworkTimeout</code> – The default network timeout value in milliseconds to wait for the database operation to complete. See the API documentation of <code>java.sql.Connection#setNetworkTimeout()</code> for details.</li>
1609+
16081610
</ul>
16091611
<p>필수는 아니지만 선택적으로 데이터베이스 드라이버에 프로퍼티를 전달할 수도 있다.
16101612
그러기 위해서는 다음 예제처럼 “driver.” 로 시작하는 접두어로 프로퍼티를 명시하면 된다.</p>

src/site/xdoc/configuration.xml

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1891,8 +1891,7 @@ SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader, propert
18911891
performance of immediately available connections. Different
18921892
databases are also different in this performance area, so for some
18931893
it may be less important to pool and this configuration will be
1894-
ideal. The UNPOOLED DataSource is configured with only five
1895-
properties:
1894+
ideal. The UNPOOLED DataSource has the following properties to configure:
18961895
</p>
18971896
<ul>
18981897
<li><code>driver</code> – This is the fully qualified Java class of the JDBC
@@ -1907,6 +1906,8 @@ SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader, propert
19071906
<li><code>defaultTransactionIsolationLevel</code> – The default transaction
19081907
isolation level for connections.
19091908
</li>
1909+
<li><code>defaultNetworkTimeout</code> – The default network timeout value in milliseconds to wait for the database operation to complete. See the API documentation of <code>java.sql.Connection#setNetworkTimeout()</code> for details.
1910+
</li>
19101911
</ul>
19111912
<p>
19121913
Optionally, you can pass properties to the database driver as

src/site/zh/xdoc/configuration.xml

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1657,7 +1657,7 @@ SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader, propert
16571657
<p>有三种内建的数据源类型(也就是 type=”[UNPOOLED|POOLED|JNDI]”):</p>
16581658
<p>
16591659
<strong>UNPOOLED</strong>– 这个数据源的实现只是每次被请求时打开和关闭连接。虽然有点慢,但对于在数据库连接可用性方面没有太高要求的简单应用程序来说,是一个很好的选择。
1660-
不同的数据库在性能方面的表现也是不一样的,对于某些数据库来说,使用连接池并不重要,这个配置就很适合这种情形。UNPOOLED 类型的数据源仅仅需要配置以下 5 种属性:</p>
1660+
不同的数据库在性能方面的表现也是不一样的,对于某些数据库来说,使用连接池并不重要,这个配置就很适合这种情形。UNPOOLED 类型的数据源具有以下属性。:</p>
16611661
<ul>
16621662
<li><code>driver</code> – 这是 JDBC 驱动的 Java 类的完全限定名(并不是 JDBC 驱动中可能包含的数据源类)。
16631663
</li>
@@ -1669,6 +1669,8 @@ SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader, propert
16691669
</li>
16701670
<li><code>defaultTransactionIsolationLevel</code> – 默认的连接事务隔离级别。
16711671
</li>
1672+
<li><code>defaultNetworkTimeout</code> – The default network timeout value in milliseconds to wait for the database operation to complete. See the API documentation of <code>java.sql.Connection#setNetworkTimeout()</code> for details.
1673+
</li>
16721674
</ul>
16731675
<p>作为可选项,你也可以传递属性给数据库驱动。只需在属性名加上“driver.”前缀即可,例如:
16741676
</p>
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/**
2+
* Copyright 2009-2019 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package org.apache.ibatis.datasource.unpooled;
18+
19+
import static org.junit.jupiter.api.Assertions.*;
20+
21+
import java.sql.Connection;
22+
23+
import org.apache.ibatis.datasource.pooled.PooledDataSource;
24+
import org.apache.ibatis.testcontainers.PgContainer;
25+
import org.junit.jupiter.api.Tag;
26+
import org.junit.jupiter.api.Test;
27+
28+
@Tag("TestcontainersTests")
29+
public class NetworkTimeoutTest {
30+
31+
@Test
32+
void testNetworkTimeout_UnpooledDataSource() throws Exception {
33+
UnpooledDataSource dataSource = (UnpooledDataSource) PgContainer.getUnpooledDataSource();
34+
dataSource.setDefaultNetworkTimeout(5000);
35+
try (Connection connection = dataSource.getConnection()) {
36+
assertEquals(5000, connection.getNetworkTimeout());
37+
}
38+
}
39+
40+
@Test
41+
void testNetworkTimeout_PooledDataSource() throws Exception {
42+
UnpooledDataSource unpooledDataSource = (UnpooledDataSource) PgContainer.getUnpooledDataSource();
43+
PooledDataSource dataSource = new PooledDataSource(unpooledDataSource);
44+
dataSource.setDefaultNetworkTimeout(5000);
45+
try (Connection connection = dataSource.getConnection()) {
46+
assertEquals(5000, connection.getNetworkTimeout());
47+
}
48+
}
49+
50+
}

0 commit comments

Comments
 (0)