Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down Expand Up @@ -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;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -48,6 +49,7 @@ public class UnpooledDataSource implements DataSource {

private Boolean autoCommit;
private Integer defaultTransactionIsolationLevel;
private Integer defaultNetworkTimeout;

static {
Enumeration<Driver> drivers = DriverManager.getDrivers();
Expand Down Expand Up @@ -182,6 +184,24 @@ public void setDefaultTransactionIsolationLevel(Integer defaultTransactionIsolat
this.defaultTransactionIsolationLevel = defaultTransactionIsolationLevel;
}

/**
* @since 3.5.2
*/
public Integer getDefaultNetworkTimeout() {
return defaultNetworkTimeout;
}

/**
* 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 defaultNetworkTimeout) {
this.defaultNetworkTimeout = defaultNetworkTimeout;
}

private Connection doGetConnection(String username, String password) throws SQLException {
Properties props = new Properties();
if (driverProperties != null) {
Expand Down Expand Up @@ -224,6 +244,9 @@ private synchronized void initializeDriver() throws SQLException {
}

private void configureConnection(Connection conn) throws SQLException {
if (defaultNetworkTimeout != null) {
conn.setNetworkTimeout(Executors.newSingleThreadExecutor(), defaultNetworkTimeout);
}
if (autoCommit != null && autoCommit != conn.getAutoCommit()) {
conn.setAutoCommit(autoCommit);
}
Expand Down
4 changes: 3 additions & 1 deletion src/site/es/xdoc/configuration.xml
Original file line number Diff line number Diff line change
Expand Up @@ -1627,7 +1627,7 @@ SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader,properti
</ul>
<p>Hay tres tipos de dataSources pre-construidos (ej. type=”????”):</p>
<p>
<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:
<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:
</p>
<ul>
<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>
Expand All @@ -1639,6 +1639,8 @@ SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader,properti
</li>
<li><code>defaultTransactionIsolationLevel</code> – El nivel de aislamiento por defecto con el que se crearán las conexiones.
</li>
<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>
</ul>
<p>Opcionalmente, puedes también pasar propiedades al driver de la base de datos. Para ello prefija las propiedades con “driver.”, por ejemplo:
</p>
Expand Down
6 changes: 4 additions & 2 deletions src/site/ja/xdoc/configuration.xml
Original file line number Diff line number Diff line change
Expand Up @@ -1717,7 +1717,7 @@ SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader,properti
少々遅いですが、即時の接続を必要としないシンプルなアプリケーションの場合は良い選択肢です。
パフォーマンスに関しては、お使いのデータベースによっても変わってきます。
接続プールの重要性が低いデータベースの場合はこの設定が最適となります。
UNPOOLED データソースは5つのプロパティで設定できます
UNPOOLED データソースに対して設定可能なプロパティは下記の通りです
</p>
<ul>
<li>driver – JDBC ドライバーの完全修飾 Java クラス名(ドライバーに含まれているデータソースクラスではありません)
Expand All @@ -1730,6 +1730,8 @@ SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader,properti
</li>
<li>defaultTransactionIsolationLevel – デフォルトのトランザクション分離レベル
</li>
<li>defaultNetworkTimeout – 任意の要求に対するデータベースからの応答待機期限のデフォルト値(ミリ秒)。詳細は <code>java.sql.Connection#setNetworkTimeout()</code> の javadoc 参照。
</li>
</ul>
<p>
オプションとして、データベースドライバーのプロパティを設定することもできます。
Expand All @@ -1749,7 +1751,7 @@ SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader,properti
Web アプリケーションでは応答速度向上のために良く使われる設定です。
</p>
<p>
POOLED データソースには、UNPOOLED の設定で見た5つの他に様々なプロパティを指定することができます
POOLED データソースには、UNPOOLED に対して設定可能なプロパティに加えて以下を指定することができます
</p>
<ul>
<li>poolMaximumActiveConnections – 同時にプールされる接続数の最大値です。
Expand Down
4 changes: 3 additions & 1 deletion src/site/ko/xdoc/configuration.xml
Original file line number Diff line number Diff line change
Expand Up @@ -1598,13 +1598,15 @@ SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader,properti
<p>
<strong>UNPOOLED</strong> - 이 구현체는 매번 요청에 대해 커넥션을 열고 닫는 간단한 DataSource이다.
조금 늦긴 하지만 성능을 크게 필요로 하지 않는 간단한 애플리케이션을 위해서는 괜찮은 선택이다.
UNPOOLED DataSource는 5 개의 프로퍼티만으로 설정한다.</p>
UNPOOLED DataSource에는 다음과 같은 속성이 있습니다.</p>
<ul>
<li><code>driver</code> - JDBC드라이버의 패키지 경로를 포함한 결제 자바 클래스명</li>
<li><code>url</code> - 데이터베이스 인스턴스에 대한 JDBC URL</li>
<li><code>username</code> - 데이터베이스에 로그인 할 때 사용할 사용자명</li>
<li><code>password</code> - 데이터베이스에 로그인 할 때 사용할 패스워드</li>
<li><code>defaultTransactionIsolationLevel</code> - 커넥션에 대한 디폴트 트랜잭션 격리 레벨</li>
<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>

</ul>
<p>필수는 아니지만 선택적으로 데이터베이스 드라이버에 프로퍼티를 전달할 수도 있다.
그러기 위해서는 다음 예제처럼 “driver.” 로 시작하는 접두어로 프로퍼티를 명시하면 된다.</p>
Expand Down
5 changes: 3 additions & 2 deletions src/site/xdoc/configuration.xml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
</p>
<ul>
<li><code>driver</code> – This is the fully qualified Java class of the JDBC
Expand All @@ -1907,6 +1906,8 @@ SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader, propert
<li><code>defaultTransactionIsolationLevel</code> – The default transaction
isolation level for connections.
</li>
<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>
</ul>
<p>
Optionally, you can pass properties to the database driver as
Expand Down
4 changes: 3 additions & 1 deletion src/site/zh/xdoc/configuration.xml
Original file line number Diff line number Diff line change
Expand Up @@ -1657,7 +1657,7 @@ SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader, propert
<p>有三种内建的数据源类型(也就是 type=”[UNPOOLED|POOLED|JNDI]”):</p>
<p>
<strong>UNPOOLED</strong>– 这个数据源的实现只是每次被请求时打开和关闭连接。虽然有点慢,但对于在数据库连接可用性方面没有太高要求的简单应用程序来说,是一个很好的选择。
不同的数据库在性能方面的表现也是不一样的,对于某些数据库来说,使用连接池并不重要,这个配置就很适合这种情形。UNPOOLED 类型的数据源仅仅需要配置以下 5 种属性:</p>
不同的数据库在性能方面的表现也是不一样的,对于某些数据库来说,使用连接池并不重要,这个配置就很适合这种情形。UNPOOLED 类型的数据源具有以下属性。:</p>
<ul>
<li><code>driver</code> – 这是 JDBC 驱动的 Java 类的完全限定名(并不是 JDBC 驱动中可能包含的数据源类)。
</li>
Expand All @@ -1669,6 +1669,8 @@ SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader, propert
</li>
<li><code>defaultTransactionIsolationLevel</code> – 默认的连接事务隔离级别。
</li>
<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>
</ul>
<p>作为可选项,你也可以传递属性给数据库驱动。只需在属性名加上“driver.”前缀即可,例如:
</p>
Expand Down
Original file line number Diff line number Diff line change
@@ -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());
}
}

}