Java Code Examples for com.zaxxer.hikari.HikariDataSource#close()

The following examples show how to use com.zaxxer.hikari.HikariDataSource#close() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DataSourceTerminationTask.java    From apollo-use-cases with Apache License 2.0 6 votes vote down vote up
/**
 * @see <a href="https://github.com/brettwooldridge/HikariCP/issues/742">Support graceful shutdown of connection
 * pool</a>
 */
private boolean terminateHikariDataSource(HikariDataSource dataSource) {
  HikariPoolMXBean poolMXBean = dataSource.getHikariPoolMXBean();

  //evict idle connections
  poolMXBean.softEvictConnections();

  if (poolMXBean.getActiveConnections() > 0 && retryTimes < MAX_RETRY_TIMES) {
    logger.warn("Data source {} still has {} active connections, will retry in {} ms.", dataSource,
        poolMXBean.getActiveConnections(), RETRY_DELAY_IN_MILLISECONDS);
    return false;
  }

  if (poolMXBean.getActiveConnections() > 0) {
    logger.warn("Retry times({}) >= {}, force closing data source {}, with {} active connections!", retryTimes,
        MAX_RETRY_TIMES, dataSource, poolMXBean.getActiveConnections());
  }

  dataSource.close();

  return true;
}
 
Example 2
Source File: DynamicTenantAwareRoutingSource.java    From SpringBootMultiTenancy with MIT License 6 votes vote down vote up
private void removeObsoleteTenants(DatabaseConfiguration[] configurations) {

        // Are there Tenants, that have been removed:
        Set<String> tenantNamesFromConfiguration = Arrays.stream(configurations)
                .map(x -> x.getTenant())
                .collect(Collectors.toSet());

        for (String tenant : tenants.keySet()) {

            // There is currently a Tenant, which is not listed anymore:
            if(!tenantNamesFromConfiguration.contains(tenant)) {

                // So get the DataSource first ...
                HikariDataSource dataSource = tenants.get(tenant);

                // ... close all existing connections:
                dataSource.close();

                // ... and remove it:
                tenants.remove(tenant);
            }
        }
    }
 
Example 3
Source File: MySQLDAOTestUtil.java    From conductor with Apache License 2.0 6 votes vote down vote up
private void createDatabase(String dbName) {
    HikariDataSource dataSource = new HikariDataSource();
    dataSource.setJdbcUrl("jdbc:mysql://localhost:33307/conductor");
    dataSource.setUsername("root");
    dataSource.setPassword("root");
    dataSource.setAutoCommit(false);

    dataSource.setMaximumPoolSize(2);

    try (Connection connection = dataSource.getConnection()) {
        try(Statement statement = connection.createStatement()) {
            statement.execute("CREATE DATABASE IF NOT EXISTS "+dbName);
        }
    } catch (SQLException sqlException) {
        logger.error("Unable to create default connection for docker mysql db", sqlException);
        throw new RuntimeException(sqlException);
    }finally {
        dataSource.close();
    }
}
 
Example 4
Source File: HikariCpIT.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Test
public void defaultTest2() throws InterruptedException, SQLException {
    HikariDataSource dataSource = new HikariDataSource();
    dataSource.setDataSourceClassName(DATA_SOURCE_CLASS_NAME);
    dataSource.addDataSourceProperty("url", JDBC_URL);

    try {
        Connection connection = dataSource.getConnection();
        Assert.assertNotNull(connection);

        Thread.sleep(500);

        connection.close();

        Thread.sleep(500);

        PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
        verifier.printCache();

        verifier.verifyTrace(event(serviceType, "com.zaxxer.hikari.HikariDataSource.HikariDataSource()"));
        verifier.verifyTrace(event(serviceType, getConnectionMethod1));
        verifier.verifyTrace(event(serviceType, "com.zaxxer.hikari.pool.BaseHikariPool.BaseHikariPool(com.zaxxer.hikari.HikariConfig, java.lang.String, java.lang.String)"));
        verifier.verifyTrace(event(serviceType, proxyConnectionMethod));

    } finally {
        if (dataSource != null) {
            dataSource.close();
        }
    }
}
 
Example 5
Source File: HikariCpJDK7IT.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Test
public void defaultTest3() throws InterruptedException, SQLException, NoSuchMethodException {
    HikariDataSource dataSource = new HikariDataSource();
    dataSource.setDataSourceClassName(DATA_SOURCE_CLASS_NAME);
    dataSource.addDataSourceProperty("url", JDBC_URL);

    try {
        Connection connection = dataSource.getConnection("", "");
        Assert.assertNotNull(connection);

        Thread.sleep(500);

        connection.close();

        Thread.sleep(500);

        PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
        verifier.printCache();

        verifier.verifyTrace(event(serviceType, "com.zaxxer.hikari.HikariDataSource.HikariDataSource()"));
        verifier.verifyTrace(event(serviceType, getConnectionMethod2, annotation(AnnotationKey.ARGS0.getName(), "")));
        verifier.verifyTrace(event(serviceType, proxyConnectionMethod));
    } finally {
        if (dataSource != null) {
            dataSource.close();
        }
    }
}
 
Example 6
Source File: ConnectionPoolContextListener.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Override
public void contextDestroyed(ServletContextEvent event) {
  // This function is called when the Servlet is destroyed.
  HikariDataSource pool = (HikariDataSource) event.getServletContext().getAttribute("my-pool");
  if (pool != null) {
    pool.close();
  }
}
 
Example 7
Source File: ConnectionPoolContextListener.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Override
public void contextDestroyed(ServletContextEvent event) {
  // This function is called when the Servlet is destroyed.
  HikariDataSource pool = (HikariDataSource) event.getServletContext().getAttribute("my-pool");
  if (pool != null) {
    pool.close();
  }
}
 
Example 8
Source File: OracleJDBCDriverTest.java    From testcontainers-java with MIT License 5 votes vote down vote up
private void performSimpleTest(String jdbcUrl) throws SQLException {
    HikariDataSource dataSource = getDataSource(jdbcUrl, 1);
    new QueryRunner(dataSource).query("SELECT 1 FROM dual", new ResultSetHandler<Object>() {
        @Override
        public Object handle(ResultSet rs) throws SQLException {
            rs.next();
            int resultSetInt = rs.getInt(1);
            assertEquals("A basic SELECT query succeeds", 1, resultSetInt);
            return true;
        }
    });
    dataSource.close();
}
 
Example 9
Source File: WaltzApplication.java    From waltz with Apache License 2.0 5 votes vote down vote up
@Override
public void destroy() {
    AnnotationConfigApplicationContext ctx = Main.getSpringContext();
    if (ctx != null) {
        HikariDataSource dataSource = ctx.getBean(HikariDataSource.class);
        if (dataSource != null) {
            dataSource.close();
        }
        ctx.close();
    }
}
 
Example 10
Source File: DataSourceManager.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
/**
 * Close, close cached data source.
 */
@Override
public void close() {
    for (HikariDataSource each : cachedDataSources.values()) {
        if (!each.isClosed()) {
            each.close();
        }
    }
    cachedDataSources.clear();
    sourceDatasources.clear();
}
 
Example 11
Source File: Neo4JDriverDecorator.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@Override
public void afterAll(final TestInvocation invocation) throws Exception {
    final ExecutionContext context = invocation.getContext();
    final HikariDataSource ds = (HikariDataSource) context.getData(Constants.KEY_DATA_SOURCE);
    ds.close();
    context.storeData(Constants.KEY_DATA_SOURCE, null);
}
 
Example 12
Source File: CodeGenServiceImpl.java    From spring-boot-demo with MIT License 5 votes vote down vote up
@SneakyThrows
private List<Entity> queryColumns(TableRequest request) {
    HikariDataSource dataSource = DbUtil.buildFromTableRequest(request);
    Db db = new Db(dataSource);

    List<Entity> query = db.query(COLUMN_SQL_TEMPLATE, request.getTableName());

    dataSource.close();
    return query;
}
 
Example 13
Source File: CodeGenServiceImpl.java    From spring-boot-demo with MIT License 5 votes vote down vote up
@SneakyThrows
private Entity queryTable(TableRequest request) {
    HikariDataSource dataSource = DbUtil.buildFromTableRequest(request);
    Db db = new Db(dataSource);

    String paramSql = StrUtil.EMPTY;
    if (StrUtil.isNotBlank(request.getTableName())) {
        paramSql = "and table_name = ?";
    }
    String sql = String.format(TABLE_SQL_TEMPLATE, paramSql);
    Entity entity = db.queryOne(sql, request.getTableName());

    dataSource.close();
    return entity;
}
 
Example 14
Source File: HikariCpIT.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Test
public void defaultTest3() throws InterruptedException, SQLException {
    HikariDataSource dataSource = new HikariDataSource();
    dataSource.setDataSourceClassName(DATA_SOURCE_CLASS_NAME);
    dataSource.addDataSourceProperty("url", JDBC_URL);

    try {
        Connection connection = dataSource.getConnection("", "");
        Assert.assertNotNull(connection);

        Thread.sleep(500);

        connection.close();

        Thread.sleep(500);

        PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
        verifier.printCache();

        verifier.verifyTrace(event(serviceType, "com.zaxxer.hikari.HikariDataSource.HikariDataSource()"));
        verifier.verifyTrace(event(serviceType, getConnectionMethod2, annotation(AnnotationKey.ARGS0.getName(), "")));
        verifier.verifyTrace(event(serviceType, proxyConnectionMethod));
    } finally {
        if (dataSource != null) {
            dataSource.close();
        }
    }
}
 
Example 15
Source File: DataSourceManager.java    From apollo-use-cases with Apache License 2.0 5 votes vote down vote up
public HikariDataSource createAndTestDataSource() throws SQLException {
  HikariDataSource newDataSource = createDataSource();
  try {
    testConnection(newDataSource);
  } catch (SQLException ex) {
    logger.error("Testing connection for data source failed: {}", newDataSource.getJdbcUrl(), ex);
    newDataSource.close();
    throw ex;
  }

  return newDataSource;
}
 
Example 16
Source File: MySqlIntegrationTest.java    From AuthMeReloaded with GNU General Public License v3.0 4 votes vote down vote up
private static void silentClose(HikariDataSource con) {
    if (con != null && !con.isClosed()) {
        con.close();
    }
}
 
Example 17
Source File: HikariCpJDK7IT.java    From pinpoint with Apache License 2.0 4 votes vote down vote up
@Test
public void defaultTest2() throws InterruptedException, SQLException, NoSuchMethodException {
    HikariDataSource dataSource = new HikariDataSource();
    dataSource.setDataSourceClassName(DATA_SOURCE_CLASS_NAME);
    dataSource.addDataSourceProperty("url", JDBC_URL);

    try {
        Connection connection = dataSource.getConnection();
        Assert.assertNotNull(connection);

        Thread.sleep(500);

        connection.close();

        Thread.sleep(500);

        PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
        verifier.printCache();

        verifier.verifyTrace(event(serviceType, "com.zaxxer.hikari.HikariDataSource.HikariDataSource()"));
        verifier.verifyTrace(event(serviceType, getConnectionMethod1));
        verifier.verifyTrace(event(serviceType, "com.zaxxer.hikari.pool.BaseHikariPool.BaseHikariPool(com.zaxxer.hikari.HikariConfig, java.lang.String, java.lang.String)"));
        verifier.verifyTrace(event(serviceType, proxyConnectionMethod));

    } finally {
        if (dataSource != null) {
            dataSource.close();
        }
    }
}
 
Example 18
Source File: PostgreSqlIntegrationTest.java    From AuthMeReloaded with GNU General Public License v3.0 4 votes vote down vote up
private static void silentClose(HikariDataSource con) {
    if (con != null && !con.isClosed()) {
        con.close();
    }
}
 
Example 19
Source File: JdbcDataSourceService.java    From poli with MIT License 4 votes vote down vote up
@PreDestroy
public void shutdown() {
    for (HikariDataSource hiDs : DATA_SOURCE_CACHE.asMap().values()) {
        hiDs.close();
    }
}
 
Example 20
Source File: AbstractJDBCDriverTest.java    From testcontainers-java with MIT License 3 votes vote down vote up
/**
 * This method intentionally verifies encoding twice to ensure that the query string parameters are used when
 * Connections are created from cached containers.
 *
 * @param jdbcUrl
 * @throws SQLException
 */
private void performSimpleTestWithCharacterSet(String jdbcUrl) throws SQLException {
    HikariDataSource datasource1 = verifyCharacterSet(jdbcUrl);
    HikariDataSource datasource2 = verifyCharacterSet(jdbcUrl);
    datasource1.close();
    datasource2.close();
}