jdbc OracleDataSource在执行语句后未释放连接

时间:2018-08-14 10:24:10

标签: java jdbc connection-pooling

我正在使用以下设置从oracle DB和连接池中获取数据。

在此设置上执行getConnection时,oracle数据源始终创建新连接并返回,直到达到最大限制。即使我执行完该语句。如何释放连接?

我知道我可以使用apache dpcp或oracle upc,但是我想修复以下代码,并且不能使用任何其他框架。

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import oracle.jdbc.pool.OracleConnectionCacheManager;
import oracle.jdbc.pool.OracleDataSource;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;


public class DatabaseUtility {
  private static final String CACHE_NAME = "DBCACHE";
  private static OracleDataSource ods = null;
  private static final Logger LOGGER = LogManager.getLogger(DatabaseUtility.class);

  public static synchronized void init(Properties properties) throws SQLException {

    if (ods == null) {
      LOGGER.info("OracleDataSource Initialization");
      ods = new OracleDataSource();
      ods.setURL(PropertiesLoader.getValue(properties, "jdbc.datasource.url"));
      ods.setUser(PropertiesLoader.getValue(properties, "jdbc.datasource.username"));
      ods.setPassword(PropertiesLoader.getValue(properties, "jdbc.datasource.password"));

      ods.setConnectionCachingEnabled(true);
      ods.setConnectionCacheName(CACHE_NAME);
      Properties cacheProps = new Properties();
      cacheProps.setProperty(
          "MinLimit", PropertiesLoader.getValue(properties, "jdbc.datasource.minlimit"));
      cacheProps.setProperty(
          "MaxLimit", PropertiesLoader.getValue(properties, "jdbc.datasource.maxlimit"));
      cacheProps.setProperty(
          "InitialLimit", PropertiesLoader.getValue(properties, "jdbc.datasource.minlimit"));
      cacheProps.setProperty(
          "ConnectionWaitTimeout", PropertiesLoader.getValue(properties, "jdbc.datasource.wait"));
      cacheProps.setProperty(
          "ValidateConnection",
          PropertiesLoader.getValue(properties, "jdbc.datasource.validate"));

      ods.setConnectionCacheProperties(cacheProps);
    }
  }

  private DatabaseUtility() {
    throw new AssertionError("Can not create object of DatabaseUtility!");
  }

  public static synchronized Connection getConnection(Properties properties) throws SQLException {
    LOGGER.info("Request connection!");
    if (ods == null) {
      init(properties);
    }
    return ods.getConnection();
  }

  public static void closePooledConnections() throws SQLException {
    if (ods != null) {
      ods.close();
    }
  }

  public static void listCacheInfos() throws SQLException {
    OracleConnectionCacheManager occm =
        OracleConnectionCacheManager.getConnectionCacheManagerInstance();
    LOGGER.info(
        occm.getNumberOfAvailableConnections(CACHE_NAME)
            + " connections are available in cache "
            + CACHE_NAME);
    LOGGER.info(occm.getNumberOfActiveConnections(CACHE_NAME) + " connections are active");
  }
}

那么,执行完查询后如何释放连接以供重用?

0 个答案:

没有答案