diff --git a/src/main/java/org/apache/ibatis/datasource/pooled/PooledDataSource.java b/src/main/java/org/apache/ibatis/datasource/pooled/PooledDataSource.java
index 718a8a5bdc3..20201a38d43 100644
--- a/src/main/java/org/apache/ibatis/datasource/pooled/PooledDataSource.java
+++ b/src/main/java/org/apache/ibatis/datasource/pooled/PooledDataSource.java
@@ -149,6 +149,18 @@ public void setDriverProperties(Properties driverProps) {
forceCloseAll();
}
+ /**
+ * Sets the default network timeout value to wait for the database operation to complete. See {@link Connection#setNetworkTimeout(java.util.concurrent.Executor, int)}
+ *
+ * @param milliseconds
+ * The time in milliseconds to wait for the database operation to complete.
+ * @since 3.5.2
+ */
+ public void setDefaultNetworkTimeout(Integer milliseconds) {
+ dataSource.setDefaultNetworkTimeout(milliseconds);
+ forceCloseAll();
+ }
+
/**
* The maximum number of active connections.
*
@@ -263,6 +275,13 @@ public Properties getDriverProperties() {
return dataSource.getDriverProperties();
}
+ /**
+ * @since 3.5.2
+ */
+ public Integer getDefaultNetworkTimeout() {
+ return dataSource.getDefaultNetworkTimeout();
+ }
+
public int getPoolMaximumActiveConnections() {
return poolMaximumActiveConnections;
}
diff --git a/src/main/java/org/apache/ibatis/datasource/unpooled/UnpooledDataSource.java b/src/main/java/org/apache/ibatis/datasource/unpooled/UnpooledDataSource.java
index 0e857ba5716..31f43b8463f 100644
--- a/src/main/java/org/apache/ibatis/datasource/unpooled/UnpooledDataSource.java
+++ b/src/main/java/org/apache/ibatis/datasource/unpooled/UnpooledDataSource.java
@@ -25,6 +25,7 @@
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.Executors;
import java.util.logging.Logger;
import javax.sql.DataSource;
@@ -48,6 +49,7 @@ public class UnpooledDataSource implements DataSource {
private Boolean autoCommit;
private Integer defaultTransactionIsolationLevel;
+ private Integer defaultNetworkTimeout;
static {
Enumeration Hay tres tipos de dataSources pre-construidos (ej. type=”????”):
- UNPOOLED – 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:
+ UNPOOLED – 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:
Opcionalmente, puedes también pasar propiedades al driver de la base de datos. Para ello prefija las propiedades con “driver.”, por ejemplo:
driver – 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).defaultTransactionIsolationLevel – El nivel de aislamiento por defecto con el que se crearán las conexiones.
defaultNetworkTimeout – The default network timeout value in milliseconds to wait for the database operation to complete. See the API documentation of java.sql.Connection#setNetworkTimeout() for details.
+
java.sql.Connection#setNetworkTimeout() の javadoc 参照。
+ オプションとして、データベースドライバーのプロパティを設定することもできます。 @@ -1749,7 +1751,7 @@ SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader,properti Web アプリケーションでは応答速度向上のために良く使われる設定です。
- POOLED データソースには、UNPOOLED の設定で見た5つの他に様々なプロパティを指定することができます。 + POOLED データソースには、UNPOOLED に対して設定可能なプロパティに加えて以下を指定することができます。
UNPOOLED - 이 구현체는 매번 요청에 대해 커넥션을 열고 닫는 간단한 DataSource이다. 조금 늦긴 하지만 성능을 크게 필요로 하지 않는 간단한 애플리케이션을 위해서는 괜찮은 선택이다. - UNPOOLED DataSource는 5 개의 프로퍼티만으로 설정한다.
+ UNPOOLED DataSource에는 다음과 같은 속성이 있습니다.driver - JDBC드라이버의 패키지 경로를 포함한 결제 자바 클래스명url - 데이터베이스 인스턴스에 대한 JDBC URLusername - 데이터베이스에 로그인 할 때 사용할 사용자명password - 데이터베이스에 로그인 할 때 사용할 패스워드defaultTransactionIsolationLevel - 커넥션에 대한 디폴트 트랜잭션 격리 레벨defaultNetworkTimeout – The default network timeout value in milliseconds to wait for the database operation to complete. See the API documentation of java.sql.Connection#setNetworkTimeout() for details.필수는 아니지만 선택적으로 데이터베이스 드라이버에 프로퍼티를 전달할 수도 있다. 그러기 위해서는 다음 예제처럼 “driver.” 로 시작하는 접두어로 프로퍼티를 명시하면 된다.
diff --git a/src/site/xdoc/configuration.xml b/src/site/xdoc/configuration.xml index 53ff8828f69..76beaa7b4e7 100644 --- a/src/site/xdoc/configuration.xml +++ b/src/site/xdoc/configuration.xml @@ -1891,8 +1891,7 @@ SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader, propert performance of immediately available connections. Different databases are also different in this performance area, so for some it may be less important to pool and this configuration will be - ideal. The UNPOOLED DataSource is configured with only five - properties: + ideal. The UNPOOLED DataSource has the following properties to configure:driver – This is the fully qualified Java class of the JDBC
@@ -1907,6 +1906,8 @@ SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader, propert
defaultTransactionIsolationLevel – The default transaction
isolation level for connections.
defaultNetworkTimeout – The default network timeout value in milliseconds to wait for the database operation to complete. See the API documentation of java.sql.Connection#setNetworkTimeout() for details.
+ Optionally, you can pass properties to the database driver as diff --git a/src/site/zh/xdoc/configuration.xml b/src/site/zh/xdoc/configuration.xml index 61ac4f88149..17f5849127f 100644 --- a/src/site/zh/xdoc/configuration.xml +++ b/src/site/zh/xdoc/configuration.xml @@ -1657,7 +1657,7 @@ SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader, propert
有三种内建的数据源类型(也就是 type=”[UNPOOLED|POOLED|JNDI]”):
UNPOOLED– 这个数据源的实现只是每次被请求时打开和关闭连接。虽然有点慢,但对于在数据库连接可用性方面没有太高要求的简单应用程序来说,是一个很好的选择。 - 不同的数据库在性能方面的表现也是不一样的,对于某些数据库来说,使用连接池并不重要,这个配置就很适合这种情形。UNPOOLED 类型的数据源仅仅需要配置以下 5 种属性:
+ 不同的数据库在性能方面的表现也是不一样的,对于某些数据库来说,使用连接池并不重要,这个配置就很适合这种情形。UNPOOLED 类型的数据源具有以下属性。:driver – 这是 JDBC 驱动的 Java 类的完全限定名(并不是 JDBC 驱动中可能包含的数据源类)。
defaultTransactionIsolationLevel – 默认的连接事务隔离级别。
defaultNetworkTimeout – The default network timeout value in milliseconds to wait for the database operation to complete. See the API documentation of java.sql.Connection#setNetworkTimeout() for details.
+ 作为可选项,你也可以传递属性给数据库驱动。只需在属性名加上“driver.”前缀即可,例如:
diff --git a/src/test/java/org/apache/ibatis/datasource/unpooled/NetworkTimeoutTest.java b/src/test/java/org/apache/ibatis/datasource/unpooled/NetworkTimeoutTest.java new file mode 100644 index 00000000000..32477db80d4 --- /dev/null +++ b/src/test/java/org/apache/ibatis/datasource/unpooled/NetworkTimeoutTest.java @@ -0,0 +1,50 @@ +/** + * Copyright 2009-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.ibatis.datasource.unpooled; + +import static org.junit.jupiter.api.Assertions.*; + +import java.sql.Connection; + +import org.apache.ibatis.datasource.pooled.PooledDataSource; +import org.apache.ibatis.testcontainers.PgContainer; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +@Tag("TestcontainersTests") +public class NetworkTimeoutTest { + + @Test + void testNetworkTimeout_UnpooledDataSource() throws Exception { + UnpooledDataSource dataSource = (UnpooledDataSource) PgContainer.getUnpooledDataSource(); + dataSource.setDefaultNetworkTimeout(5000); + try (Connection connection = dataSource.getConnection()) { + assertEquals(5000, connection.getNetworkTimeout()); + } + } + + @Test + void testNetworkTimeout_PooledDataSource() throws Exception { + UnpooledDataSource unpooledDataSource = (UnpooledDataSource) PgContainer.getUnpooledDataSource(); + PooledDataSource dataSource = new PooledDataSource(unpooledDataSource); + dataSource.setDefaultNetworkTimeout(5000); + try (Connection connection = dataSource.getConnection()) { + assertEquals(5000, connection.getNetworkTimeout()); + } + } + +}