Java Code Examples for com.alibaba.druid.pool.DruidDataSource#close()

The following examples show how to use com.alibaba.druid.pool.DruidDataSource#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: DataSourceCachePool.java    From jeecg-cloud with Apache License 2.0 5 votes vote down vote up
/**
 * 清空数据源缓存
 */
public static void cleanAllCache() {
    //关闭数据源连接
    for(Map.Entry<String, DruidDataSource> entry : dbSources.entrySet()){
        String dbkey = entry.getKey();
        DruidDataSource druidDataSource = entry.getValue();
        if(druidDataSource!=null && druidDataSource.isEnable()){
            druidDataSource.close();
        }
        //清空redis缓存
        getRedisTemplate().delete(CacheConstant.SYS_DYNAMICDB_CACHE + dbkey);
    }
    //清空缓存
    dbSources.clear();
}
 
Example 2
Source File: DataSourceCachePool.java    From jeecg-cloud with Apache License 2.0 5 votes vote down vote up
public static void removeCache(String dbKey) {
    //关闭数据源连接
    DruidDataSource druidDataSource = dbSources.get(dbKey);
    if(druidDataSource!=null && druidDataSource.isEnable()){
        druidDataSource.close();
    }
    //清空redis缓存
    getRedisTemplate().delete(CacheConstant.SYS_DYNAMICDB_CACHE + dbKey);
    //清空缓存
    dbSources.remove(dbKey);
}
 
Example 3
Source File: DynamicDBUtil.java    From jeecg-cloud with Apache License 2.0 5 votes vote down vote up
/**
 * 关闭数据库连接池
 *
 * @param dbKey
 * @return
 */
public static void closeDbKey(final String dbKey) {
    DruidDataSource dataSource = getDbSourceByDbKey(dbKey);
    try {
        if (dataSource != null && !dataSource.isClosed()) {
            dataSource.getConnection().commit();
            dataSource.getConnection().close();
            dataSource.close();
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
}
 
Example 4
Source File: AbstractEventCheck.java    From DataSphereStudio with Apache License 2.0 5 votes vote down vote up
public static void closeDruidDataSource() {
    DruidDataSource msgDSObject = (DruidDataSource) msgDS;
    if (msgDSObject != null) {
        msgDSObject.close();
    }

}
 
Example 5
Source File: DataSourceCachePool.java    From jeecg-boot with Apache License 2.0 5 votes vote down vote up
/**
 * 清空数据源缓存
 */
public static void cleanAllCache() {
    //关闭数据源连接
    for(Map.Entry<String, DruidDataSource> entry : dbSources.entrySet()){
        String dbkey = entry.getKey();
        DruidDataSource druidDataSource = entry.getValue();
        if(druidDataSource!=null && druidDataSource.isEnable()){
            druidDataSource.close();
        }
        //清空redis缓存
        getRedisTemplate().delete(CacheConstant.SYS_DYNAMICDB_CACHE + dbkey);
    }
    //清空缓存
    dbSources.clear();
}
 
Example 6
Source File: DataSourceCachePool.java    From jeecg-boot with Apache License 2.0 5 votes vote down vote up
public static void removeCache(String dbKey) {
    //关闭数据源连接
    DruidDataSource druidDataSource = dbSources.get(dbKey);
    if(druidDataSource!=null && druidDataSource.isEnable()){
        druidDataSource.close();
    }
    //清空redis缓存
    getRedisTemplate().delete(CacheConstant.SYS_DYNAMICDB_CACHE + dbKey);
    //清空缓存
    dbSources.remove(dbKey);
}
 
Example 7
Source File: DynamicDBUtil.java    From jeecg-boot with Apache License 2.0 5 votes vote down vote up
/**
 * 关闭数据库连接池
 *
 * @param dbKey
 * @return
 */
public static void closeDbKey(final String dbKey) {
    DruidDataSource dataSource = getDbSourceByDbKey(dbKey);
    try {
        if (dataSource != null && !dataSource.isClosed()) {
            dataSource.getConnection().commit();
            dataSource.getConnection().close();
            dataSource.close();
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
}
 
Example 8
Source File: DynamicDataSource.java    From spring-boot-starter-dao with Apache License 2.0 5 votes vote down vote up
public void close() {
	logger.debug("销毁 DynamicDataSource {}...",this.dataSourceName);
	this.masterDataSource.close();
	Iterator<DruidDataSource> it = this.slaveDataSources.values().iterator();
	while (it.hasNext()) {
		DruidDataSource druidDataSource = (DruidDataSource) it.next();
		try {
			druidDataSource.close();
		} catch (Exception e) {
			logger.warn("关闭从库{}失败", druidDataSource.getName());
		}
	}
}
 
Example 9
Source File: DataSourceFactory.java    From yugong with GNU General Public License v2.0 5 votes vote down vote up
public void stop() {
    super.stop();

    for (DataSource source : dataSources.values()) {
        DruidDataSource basicDataSource = (DruidDataSource) source;
        basicDataSource.close();
    }

    dataSources.clear();
}
 
Example 10
Source File: ConnectionTest.java    From tddl5 with Apache License 2.0 5 votes vote down vote up
/**
 * @param args
 */
public static void main(String[] args) {
    try {
        DruidDataSource ds = new DruidDataSource();
        ds.setUsername("test");
        ds.setPassword("");
        ds.setUrl("jdbc:mysql://10.20.153.178:9066/");
        ds.setDriverClassName("com.mysql.jdbc.Driver");
        ds.setMaxActive(-1);
        ds.setMinIdle(0);
        ds.setTimeBetweenEvictionRunsMillis(600000);
        // ds.setNumTestsPerEvictionRun(Integer.MAX_VALUE);
        ds.setMinEvictableIdleTimeMillis(DruidDataSource.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS);
        Connection conn = ds.getConnection();

        Statement stm = conn.createStatement();
        stm.execute("show @@version");

        ResultSet rst = stm.getResultSet();
        rst.next();
        String version = rst.getString("VERSION");

        System.out.println(version);
        ds.close();
    } catch (Exception exception) {
        System.out.println("10.20.153.178:9066   " + exception.getMessage() + exception);
    }
}
 
Example 11
Source File: JDBCTests.java    From elasticsearch-sql with Apache License 2.0 5 votes vote down vote up
@Test
public void testJDBC() throws Exception {
    Properties properties = new Properties();
    properties.put(PROP_URL, "jdbc:elasticsearch://127.0.0.1:9300/" + TestsConstants.TEST_INDEX_ACCOUNT);
    properties.put(PROP_CONNECTIONPROPERTIES, "client.transport.ignore_cluster_name=true");
    DruidDataSource dds = (DruidDataSource) ElasticSearchDruidDataSourceFactory.createDataSource(properties);
    Connection connection = dds.getConnection();
    PreparedStatement ps = connection.prepareStatement("SELECT /*! USE_SCROLL*/ gender,lastname,age,_scroll_id from  " + TestsConstants.TEST_INDEX_ACCOUNT + " where lastname='Heath'");
    ResultSet resultSet = ps.executeQuery();

    ResultSetMetaData metaData = resultSet.getMetaData();
    assertThat(metaData.getColumnName(1), equalTo("gender"));
    assertThat(metaData.getColumnName(2), equalTo("lastname"));
    assertThat(metaData.getColumnName(3), equalTo("age"));

    List<String> result = new ArrayList<String>();
    String scrollId = null;
    while (resultSet.next()) {
        scrollId = resultSet.getString("_scroll_id");
        result.add(resultSet.getString("lastname") + "," + resultSet.getInt("age") + "," + resultSet.getString("gender"));
    }

    ps.close();
    connection.close();
    dds.close();

    Assert.assertEquals(1, result.size());
    Assert.assertEquals("Heath,39,F", result.get(0));
    Assert.assertFalse(Matchers.isEmptyOrNullString().matches(scrollId));
}
 
Example 12
Source File: DruidIT.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Test
public void test() throws InterruptedException, SQLException {

    DruidDataSource dataSource = new DruidDataSource();

    dataSource.setUrl(JDBC_URL);
    dataSource.setValidationQuery("select 'x'");
    dataSource.setUsername("test");
    dataSource.setPassword("test");

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

        connection.close();

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

        verifier.verifyTrace(event(serviceType, getConnectionMethod));
        verifier.verifyTrace(event(serviceType, closeConnectionMethod));
    } finally {
        if (dataSource != null) {
            dataSource.close();
        }
    }
}
 
Example 13
Source File: DataCheckerDao.java    From DataSphereStudio with Apache License 2.0 4 votes vote down vote up
public static void closeDruidDataSource(){
	DruidDataSource jobDSObject = (DruidDataSource)jobDS;
	if(jobDSObject != null){
		jobDSObject.close();
	}
}
 
Example 14
Source File: DBTest.java    From canal-1.1.3 with Apache License 2.0 4 votes vote down vote up
@Test
public void test01() throws SQLException {
    DruidDataSource dataSource = new DruidDataSource();
    // dataSource.setDriverClassName("oracle.jdbc.OracleDriver");
    // dataSource.setUrl("jdbc:oracle:thin:@127.0.0.1:49161:XE");
    // dataSource.setUsername("mytest");
    // dataSource.setPassword("m121212");

    dataSource.setDriverClassName("com.mysql.jdbc.Driver");
    dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/mytest?useUnicode=true");
    dataSource.setUsername("root");
    dataSource.setPassword("121212");

    dataSource.setInitialSize(1);
    dataSource.setMinIdle(1);
    dataSource.setMaxActive(2);
    dataSource.setMaxWait(60000);
    dataSource.setTimeBetweenEvictionRunsMillis(60000);
    dataSource.setMinEvictableIdleTimeMillis(300000);

    dataSource.init();

    Connection conn = dataSource.getConnection();

    conn.setAutoCommit(false);
    PreparedStatement pstmt = conn
        .prepareStatement("insert into user (id,name,role_id,c_time,test1,test2) values (?,?,?,?,?,?)");

    java.util.Date now = new java.util.Date();
    for (int i = 1; i <= 10000; i++) {
        pstmt.clearParameters();
        pstmt.setLong(1, (long) i);
        pstmt.setString(2, "test_" + i);
        pstmt.setLong(3, (long) i % 4 + 1);
        pstmt.setDate(4, new java.sql.Date(now.getTime()));
        pstmt.setString(5, null);
        pstmt.setBytes(6, null);

        pstmt.execute();
        if (i % 5000 == 0) {
            conn.commit();
        }
    }
    conn.commit();

    pstmt.close();

    // Statement stmt = conn.createStatement();
    // ResultSet rs = stmt.executeQuery("select * from user t where 1=2");
    //
    // ResultSetMetaData rsm = rs.getMetaData();
    // int cnt = rsm.getColumnCount();
    // for (int i = 1; i <= cnt; i++) {
    // System.out.println(rsm.getColumnName(i) + " " + rsm.getColumnType(i));
    // }

    // rs.close();
    // stmt.close();

    // PreparedStatement pstmt = conn
    // .prepareStatement("insert into tb_user (id,name,role_id,c_time,test1,test2)
    // values (?,?,?,?,?,?)");
    // pstmt.setBigDecimal(1, new BigDecimal("5"));
    // pstmt.setString(2, "test");
    // pstmt.setBigDecimal(3, new BigDecimal("1"));
    // pstmt.setDate(4, new Date(new java.util.Date().getTime()));
    // byte[] a = { (byte) 1, (byte) 2 };
    // pstmt.setBytes(5, a);
    // pstmt.setBytes(6, a);
    // pstmt.execute();
    //
    // pstmt.close();

    conn.close();
    dataSource.close();
}
 
Example 15
Source File: DataSourceUtil.java    From framework with Apache License 2.0 4 votes vote down vote up
private static DataSource regist(final String name, final DbParam dbParam) {
    String uid = new StringBuilder().append(dbParam.getUsername()).append(dbParam.getPassword())
        .append(dbParam.getUrl()).toString();
    dataSourceMap.put(name, uid);
    DataSource dataSource = dsMap.get(uid);
    if (dataSource == null) {
        DruidDataSource ds = new DruidDataSource();
        ds.setDbType(dbParam.getDbType());

        ds.setUrl(dbParam.getUrl());
        if (StringUtils.isNotEmpty(dbParam.getUsername())) {
            ds.setUsername(dbParam.getUsername());
            ds.setPassword(dbParam.getPassword());
        }
        if (StringUtils.isNotEmpty(dbParam.getDriverClass())) {
            ds.setDriverClassName(dbParam.getDriverClass());
        }
        else {
            ServiceLoader<Driver> drivers = ServiceLoader.load(Driver.class);
            if (drivers != null) {
                String dbType = new StringBuilder().append('.').append(dbParam.getDbType().toLowerCase())
                    .append('.').toString();
                for (Driver driver : drivers) {
                    if (driver.getClass().getName().indexOf(dbType) != -1) {
                        ds.setDriverClassName(driver.getClass().getName());
                        break;
                    }
                }
            }
        }
        ds.setInitialSize(dbParam.getInitialSize());
        ds.setMaxActive(dbParam.getMaxActive());
        ds.setMinIdle(dbParam.getMinIdle());
        ds.setMaxWait(dbParam.getMaxWait());
        ds.setValidationQuery(dbParam.getValidationQuery());
        ds.setTestOnBorrow(dbParam.isTestOnBorrow());
        ds.setTestOnReturn(dbParam.isTestOnReturn());
        ds.setTestWhileIdle(dbParam.isTestWhileIdle());
        ds.setTimeBetweenEvictionRunsMillis(dbParam.getTimeBetweenEvictionRunsMillis());
        ds.setMinEvictableIdleTimeMillis(dbParam.getMinEvictableIdleTimeMillis());
        ds.setRemoveAbandonedTimeout(dbParam.getRemoveAbandonedTimeout());
        ds.setRemoveAbandoned(dbParam.isRemoveAbandoned());
        ds.setProxyFilters(Arrays.asList(new SqlLogFilter()));
        try {
            ds.setFilters(dbParam.getFilters());
            ds.init();
            dsMap.put(uid, ds);
            dataSource = ds;
        }
        catch (SQLException e) {
            LoggerUtil.error(e);
            dataSourceMap.remove(name);
            if (ds != null) {
                ds.close();
            }
            throw new InitializationException(ErrorCodeDef.DB_DATASOURCE_NOT_SET, e, name);
        }
    }
    return dataSource;
}
 
Example 16
Source File: DBTest.java    From canal with Apache License 2.0 4 votes vote down vote up
@Test
public void test01() throws SQLException {
    DruidDataSource dataSource = new DruidDataSource();
    // dataSource.setDriverClassName("oracle.jdbc.OracleDriver");
    // dataSource.setUrl("jdbc:oracle:thin:@127.0.0.1:49161:XE");
    // dataSource.setUsername("mytest");
    // dataSource.setPassword("m121212");

    dataSource.setDriverClassName("com.mysql.jdbc.Driver");
    dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/mytest?useUnicode=true");
    dataSource.setUsername("root");
    dataSource.setPassword("121212");

    dataSource.setInitialSize(1);
    dataSource.setMinIdle(1);
    dataSource.setMaxActive(2);
    dataSource.setMaxWait(60000);
    dataSource.setTimeBetweenEvictionRunsMillis(60000);
    dataSource.setMinEvictableIdleTimeMillis(300000);

    dataSource.init();

    Connection conn = dataSource.getConnection();

    conn.setAutoCommit(false);
    PreparedStatement pstmt = conn.prepareStatement("insert into user (id,name,role_id,c_time,test1,test2) values (?,?,?,?,?,?)");

    java.util.Date now = new java.util.Date();
    for (int i = 1; i <= 10000; i++) {
        pstmt.clearParameters();
        pstmt.setLong(1, (long) i);
        pstmt.setString(2, "test_" + i);
        pstmt.setLong(3, (long) i % 4 + 1);
        pstmt.setDate(4, new java.sql.Date(now.getTime()));
        pstmt.setString(5, null);
        pstmt.setBytes(6, null);

        pstmt.execute();
        if (i % 5000 == 0) {
            conn.commit();
        }
    }
    conn.commit();

    pstmt.close();

    // Statement stmt = conn.createStatement();
    // ResultSet rs = stmt.executeQuery("select * from user t where 1=2");
    //
    // ResultSetMetaData rsm = rs.getMetaData();
    // int cnt = rsm.getColumnCount();
    // for (int i = 1; i <= cnt; i++) {
    // System.out.println(rsm.getColumnName(i) + " " +
    // rsm.getColumnType(i));
    // }

    // rs.close();
    // stmt.close();

    // PreparedStatement pstmt = conn
    // .prepareStatement("insert into tb_user
    // (id,name,role_id,c_time,test1,test2)
    // values (?,?,?,?,?,?)");
    // pstmt.setBigDecimal(1, new BigDecimal("5"));
    // pstmt.setString(2, "test");
    // pstmt.setBigDecimal(3, new BigDecimal("1"));
    // pstmt.setDate(4, new Date(new java.util.Date().getTime()));
    // byte[] a = { (byte) 1, (byte) 2 };
    // pstmt.setBytes(5, a);
    // pstmt.setBytes(6, a);
    // pstmt.execute();
    //
    // pstmt.close();

    conn.close();
    dataSource.close();
}