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

The following examples show how to use com.alibaba.druid.pool.DruidDataSource#setUsername() . 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: SingleDataSourceConfig.java    From saluki with Apache License 2.0 6 votes vote down vote up
protected DataSource createDataSource() throws SQLException {
    // special
    DruidDataSource datasource = new DruidDataSource();
    datasource.setUrl(commonProperties.getUrl());
    datasource.setUsername(commonProperties.getUsername());
    datasource.setPassword(commonProperties.getPassword());
    // common
    datasource.setDriverClassName(commonProperties.getDriverClassName());
    datasource.setInitialSize(commonProperties.getInitialSize());
    datasource.setMinIdle(commonProperties.getMinIdle());
    datasource.setMaxActive(commonProperties.getMaxActive());
    datasource.setMaxWait(commonProperties.getMaxWait());
    datasource.setTimeBetweenEvictionRunsMillis(commonProperties.getTimeBetweenEvictionRunsMillis());
    datasource.setMinEvictableIdleTimeMillis(commonProperties.getMinEvictableIdleTimeMillis());
    datasource.setValidationQuery(commonProperties.getValidationQuery());
    datasource.setTestWhileIdle(commonProperties.isTestWhileIdle());
    datasource.setTestOnBorrow(commonProperties.isTestOnBorrow());
    datasource.setTestOnReturn(commonProperties.isTestOnReturn());
    datasource.setPoolPreparedStatements(commonProperties.isPoolPreparedStatements());
    datasource.setMaxPoolPreparedStatementPerConnectionSize(
        commonProperties.getMaxPoolPreparedStatementPerConnectionSize());
    datasource.setFilters(commonProperties.getFilters());
    datasource.setConnectionProperties(commonProperties.getConnectionProperties());
    return datasource;
}
 
Example 2
Source File: JdbcCoordinatorRepository.java    From myth with Apache License 2.0 6 votes vote down vote up
@Override
public void init(final String modelName, final MythConfig mythConfig) {
    dataSource = new DruidDataSource();
    final MythDbConfig tccDbConfig = mythConfig.getMythDbConfig();
    dataSource.setUrl(tccDbConfig.getUrl());
    dataSource.setDriverClassName(tccDbConfig.getDriverClassName());
    dataSource.setUsername(tccDbConfig.getUsername());
    dataSource.setPassword(tccDbConfig.getPassword());
    dataSource.setInitialSize(tccDbConfig.getInitialSize());
    dataSource.setMaxActive(tccDbConfig.getMaxActive());
    dataSource.setMinIdle(tccDbConfig.getMinIdle());
    dataSource.setMaxWait(tccDbConfig.getMaxWait());
    dataSource.setValidationQuery(tccDbConfig.getValidationQuery());
    dataSource.setTestOnBorrow(tccDbConfig.getTestOnBorrow());
    dataSource.setTestOnReturn(tccDbConfig.getTestOnReturn());
    dataSource.setTestWhileIdle(tccDbConfig.getTestWhileIdle());
    dataSource.setPoolPreparedStatements(tccDbConfig.getPoolPreparedStatements());
    dataSource.setMaxPoolPreparedStatementPerConnectionSize(tccDbConfig.getMaxPoolPreparedStatementPerConnectionSize());
    this.tableName = RepositoryPathUtils.buildDbTableName(modelName);
    executeUpdate(SqlHelper.buildCreateTableSql(tccDbConfig.getDriverClassName(), tableName));
}
 
Example 3
Source File: DruidDataSourceConfig.java    From springBoot-swagger-mybatis-shardbatis with Apache License 2.0 6 votes vote down vote up
@Bean
  public DataSource dataSource() {
      DruidDataSource datasource = new DruidDataSource();
      datasource.setUrl(propertyResolver.getProperty("url"));
      datasource.setDriverClassName(propertyResolver.getProperty("driver-class-name"));
      datasource.setUsername(propertyResolver.getProperty("username"));
      datasource.setPassword(propertyResolver.getProperty("password"));
      datasource.setInitialSize(Integer.valueOf(propertyResolver.getProperty("initial-size")));
      datasource.setMinIdle(Integer.valueOf(propertyResolver.getProperty("min-idle")));
      datasource.setMaxWait(Long.valueOf(propertyResolver.getProperty("max-wait")));
      datasource.setMaxActive(Integer.valueOf(propertyResolver.getProperty("max-active")));
      datasource.setMinEvictableIdleTimeMillis(Long.valueOf(propertyResolver.getProperty("min-evictable-idle-time-millis")));
      try {
	datasource.setFilters("stat,wall");
} catch (SQLException e) {
	e.printStackTrace();
}
      return datasource;
  }
 
Example 4
Source File: DruidConfig.java    From sdmq with Apache License 2.0 5 votes vote down vote up
public DataSource newInstanceDruidDataSource() throws Exception {
    if (mydataSource != null) {
        return mydataSource;
    }
    DruidDataSource druidDataSource = new DruidDataSource();
    druidDataSource.setUrl(this.url);
    druidDataSource.setUsername(this.username);
    druidDataSource.setPassword(this.password);
    druidDataSource.setDriverClassName(this.driverClassName);
    druidDataSource.setInitialSize(this.initialSize);
    druidDataSource.setMaxActive(this.maxActive);
    druidDataSource.setMinIdle(this.minIdle);
    druidDataSource.setMaxWait(this.maxWait);
    druidDataSource.setTimeBetweenEvictionRunsMillis(this.timeBetweenEvictionRunsMillis);
    druidDataSource.setMinEvictableIdleTimeMillis(this.minEvictableIdleTimeMillis);
    druidDataSource.setValidationQuery(this.validationQuery);
    druidDataSource.setTestWhileIdle(this.testWhileIdle);
    druidDataSource.setTestOnBorrow(this.testOnBorrow);
    druidDataSource.setTestOnReturn(this.testOnReturn);
    druidDataSource.setPoolPreparedStatements(this.poolPreparedStatements);
    druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(this.maxPoolPreparedStatementPerConnectionSize);
    druidDataSource.setFilters(this.filters);

    try {
        if (null != druidDataSource) {
            druidDataSource.setFilters("wall,stat");
            druidDataSource.setUseGlobalDataSourceStat(true);
            druidDataSource.init();
        }
    } catch (Exception e) {
        throw new RuntimeException("load datasource error, dbProperties is :", e);
    }
    synchronized (this) {
        mydataSource = druidDataSource;
    }
    druidDataSource.init();
    return druidDataSource;
}
 
Example 5
Source File: DruidProperties.java    From SpringBootBucket with MIT License 5 votes vote down vote up
public void config(DruidDataSource dataSource) {
    dataSource.setDbType(JdbcConstants.MYSQL);
    dataSource.setUrl(url);
    dataSource.setUsername(username);
    dataSource.setPassword(password);
    dataSource.setDriverClassName(driverClassName);
    dataSource.setInitialSize(initialSize);     // 定义初始连接数
    dataSource.setMinIdle(minIdle);             // 最小空闲
    dataSource.setMaxActive(maxActive);         // 定义最大连接数
    dataSource.setMaxWait(maxWait);             // 获取连接等待超时的时间
    dataSource.setRemoveAbandoned(removeAbandoned); // 超过时间限制是否回收
    dataSource.setRemoveAbandonedTimeout(removeAbandonedTimeout); // 超过时间限制多长

    // 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
    dataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
    // 配置一个连接在池中最小生存的时间,单位是毫秒
    dataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
    // 用来检测连接是否有效的sql,要求是一个查询语句
    dataSource.setValidationQuery(validationQuery);
    // 申请连接的时候检测
    dataSource.setTestWhileIdle(testWhileIdle);
    // 申请连接时执行validationQuery检测连接是否有效,配置为true会降低性能
    dataSource.setTestOnBorrow(testOnBorrow);
    // 归还连接时执行validationQuery检测连接是否有效,配置为true会降低性能
    dataSource.setTestOnReturn(testOnReturn);
    // 打开PSCache,并且指定每个连接上PSCache的大小
    dataSource.setPoolPreparedStatements(poolPreparedStatements);
    dataSource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
    // 属性类型是字符串,通过别名的方式配置扩展插件,常用的插件有:
    // 监控统计用的filter:stat
    // 日志用的filter:log4j
    // 防御SQL注入的filter:wall
    try {
        dataSource.setFilters(filters);
    } catch (SQLException e) {
        e.printStackTrace();
    }
}
 
Example 6
Source File: DruidProperties.java    From SpringBootBucket with MIT License 5 votes vote down vote up
public void config(DruidDataSource dataSource) {
    dataSource.setDbType(JdbcConstants.MYSQL);
    dataSource.setUrl(url);
    dataSource.setUsername(username);
    dataSource.setPassword(password);
    dataSource.setDriverClassName(driverClassName);
    dataSource.setInitialSize(initialSize);     // 定义初始连接数
    dataSource.setMinIdle(minIdle);             // 最小空闲
    dataSource.setMaxActive(maxActive);         // 定义最大连接数
    dataSource.setMaxWait(maxWait);             // 获取连接等待超时的时间
    dataSource.setRemoveAbandoned(removeAbandoned); // 超过时间限制是否回收
    dataSource.setRemoveAbandonedTimeout(removeAbandonedTimeout); // 超过时间限制多长

    // 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
    dataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
    // 配置一个连接在池中最小生存的时间,单位是毫秒
    dataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
    // 用来检测连接是否有效的sql,要求是一个查询语句
    dataSource.setValidationQuery(validationQuery);
    // 申请连接的时候检测
    dataSource.setTestWhileIdle(testWhileIdle);
    // 申请连接时执行validationQuery检测连接是否有效,配置为true会降低性能
    dataSource.setTestOnBorrow(testOnBorrow);
    // 归还连接时执行validationQuery检测连接是否有效,配置为true会降低性能
    dataSource.setTestOnReturn(testOnReturn);
    // 打开PSCache,并且指定每个连接上PSCache的大小
    dataSource.setPoolPreparedStatements(poolPreparedStatements);
    dataSource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
    // 属性类型是字符串,通过别名的方式配置扩展插件,常用的插件有:
    // 监控统计用的filter:stat
    // 日志用的filter:log4j
    // 防御SQL注入的filter:wall
    try {
        dataSource.setFilters(filters);
    } catch (SQLException e) {
        e.printStackTrace();
    }
}
 
Example 7
Source File: SegmentService.java    From Leaf with Apache License 2.0 5 votes vote down vote up
public SegmentService() throws SQLException, InitException {
    Properties properties = PropertyFactory.getProperties();
    boolean flag = Boolean.parseBoolean(properties.getProperty(Constants.LEAF_SEGMENT_ENABLE, "true"));
    if (flag) {
        // Config dataSource
        dataSource = new DruidDataSource();
        dataSource.setUrl(properties.getProperty(Constants.LEAF_JDBC_URL));
        dataSource.setUsername(properties.getProperty(Constants.LEAF_JDBC_USERNAME));
        dataSource.setPassword(properties.getProperty(Constants.LEAF_JDBC_PASSWORD));
        dataSource.init();

        // Config Dao
        IDAllocDao dao = new IDAllocDaoImpl(dataSource);

        // Config ID Gen
        idGen = new SegmentIDGenImpl();
        ((SegmentIDGenImpl) idGen).setDao(dao);
        if (idGen.init()) {
            logger.info("Segment Service Init Successfully");
        } else {
            throw new InitException("Segment Service Init Fail");
        }
    } else {
        idGen = new ZeroIDGen();
        logger.info("Zero ID Gen Service Init Successfully");
    }
}
 
Example 8
Source File: DruidProperties.java    From SpringBootBucket with MIT License 5 votes vote down vote up
public void config(DruidDataSource dataSource) {
    dataSource.setDbType(JdbcConstants.MYSQL);
    dataSource.setUrl(url);
    dataSource.setUsername(username);
    dataSource.setPassword(password);
    dataSource.setDriverClassName(driverClassName);
    dataSource.setInitialSize(initialSize);     // 定义初始连接数
    dataSource.setMinIdle(minIdle);             // 最小空闲
    dataSource.setMaxActive(maxActive);         // 定义最大连接数
    dataSource.setMaxWait(maxWait);             // 获取连接等待超时的时间
    dataSource.setRemoveAbandoned(removeAbandoned); // 超过时间限制是否回收
    dataSource.setRemoveAbandonedTimeout(removeAbandonedTimeout); // 超过时间限制多长

    // 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
    dataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
    // 配置一个连接在池中最小生存的时间,单位是毫秒
    dataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
    // 用来检测连接是否有效的sql,要求是一个查询语句
    dataSource.setValidationQuery(validationQuery);
    // 申请连接的时候检测
    dataSource.setTestWhileIdle(testWhileIdle);
    // 申请连接时执行validationQuery检测连接是否有效,配置为true会降低性能
    dataSource.setTestOnBorrow(testOnBorrow);
    // 归还连接时执行validationQuery检测连接是否有效,配置为true会降低性能
    dataSource.setTestOnReturn(testOnReturn);
    // 打开PSCache,并且指定每个连接上PSCache的大小
    dataSource.setPoolPreparedStatements(poolPreparedStatements);
    dataSource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
    // 属性类型是字符串,通过别名的方式配置扩展插件,常用的插件有:
    // 监控统计用的filter:stat
    // 日志用的filter:log4j
    // 防御SQL注入的filter:wall
    try {
        dataSource.setFilters(filters);
    } catch (SQLException e) {
        e.printStackTrace();
    }
}
 
Example 9
Source File: ClusterDataSourceConfig.java    From springboot-learning-example with Apache License 2.0 5 votes vote down vote up
@Bean(name = "clusterDataSource")
public DataSource clusterDataSource() {
    DruidDataSource dataSource = new DruidDataSource();
    dataSource.setDriverClassName(driverClass);
    dataSource.setUrl(url);
    dataSource.setUsername(user);
    dataSource.setPassword(password);
    return dataSource;
}
 
Example 10
Source File: QuartzConfig.java    From mysiteforme with Apache License 2.0 5 votes vote down vote up
@Bean
public DataSource dataSource() throws SQLException {
    DruidDataSource druidDataSource = new DruidDataSource();
    druidDataSource.setUsername(username);
    druidDataSource.setPassword(password);
    druidDataSource.setDriverClassName(driver);
    druidDataSource.setUrl(url);
    druidDataSource.setMaxActive(Integer.valueOf(maxActive));
    druidDataSource.setFilters("stat,wall,log4j");
    druidDataSource.setInitialSize(Integer.valueOf(initialSize));
    return druidDataSource;
}
 
Example 11
Source File: DruidConfig.java    From mogu_blog_v2 with Apache License 2.0 5 votes vote down vote up
@Bean // 声明其为Bean实例
@Primary // 在同样的DataSource中,首先使用被标注的DataSource
public DataSource dataSource() {
    DruidDataSource datasource = new DruidDataSource();

    datasource.setUrl(this.dbUrl);
    datasource.setUsername(username);
    datasource.setPassword(password);
    datasource.setDriverClassName(driverClassName);

    // configuration
    datasource.setInitialSize(initialSize);
    datasource.setMinIdle(minIdle);
    datasource.setMaxActive(maxActive);
    datasource.setMaxWait(maxWait);
    datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
    datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
    datasource.setValidationQuery(validationQuery);
    datasource.setTestWhileIdle(testWhileIdle);
    datasource.setTestOnBorrow(testOnBorrow);
    datasource.setTestOnReturn(testOnReturn);
    datasource.setPoolPreparedStatements(poolPreparedStatements);
    datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
    try {
        datasource.setFilters(filters);
    } catch (SQLException e) {
        log.error("druid configuration initialization filter");
    }
    datasource.setConnectionProperties(connectionProperties);

    return datasource;
}
 
Example 12
Source File: DbNodeServiceImpl.java    From pmq with Apache License 2.0 5 votes vote down vote up
public void initDataSource(DbNodeEntity t1, String key, Map<String, DataSource> dataMap, boolean isMaster,
		Transaction transaction) {
	try {
		// if (soaConfig.isUseDruid())
		{
			DruidDataSource dataSource = dataSourceFactory.createDataSource();
			dataSource.setDriverClassName("com.mysql.jdbc.Driver");
			if (isMaster) {
				dataSource.setUsername(t1.getDbUserName());
				dataSource.setPassword(t1.getDbPass());
			} else {
				dataSource.setUsername(t1.getDbUserNameBak());
				dataSource.setPassword(t1.getDbPassBak());
			}
			// dataSource.setUrl(t1.getConStr());
			dataSource.setUrl(getCon(t1, isMaster));
			dataSource.setInitialSize(soaConfig.getInitDbCount());
			dataSource.setMinIdle(soaConfig.getInitDbCount());
			dataSource.setMaxActive(soaConfig.getMaxDbCount());
			dataSource.setConnectionInitSqls(Arrays.asList("set names utf8mb4;"));
			dataSource.init();
			dbCreated.put(key, true);
			log.info(dataSource.getUrl() + "数据源创建成功!dataSource_created");
			dataMap.put(key, dataSource);
			transaction.setStatus(Transaction.SUCCESS);
		}
	} catch (Exception e) {
		transaction.setStatus(e);
		log.error("initDataSource_error", e);
	}
}
 
Example 13
Source File: DbNodeServiceImpl.java    From pmq with Apache License 2.0 5 votes vote down vote up
private void checkMaster(DbNodeEntity dbNodeEntity) throws SQLException {
	DruidDataSource dataSource = dataSourceFactory.createDataSource();
	dataSource.setDriverClassName("com.mysql.jdbc.Driver");
	dataSource.setUsername(dbNodeEntity.getDbUserName());
	dataSource.setPassword(dbNodeEntity.getDbPass());
	dataSource.setUrl(getCon(dbNodeEntity, true));
	dataSource.setInitialSize(1);
	dataSource.setMinIdle(0);
	dataSource.setMaxActive(1);
	dataSource.init();
	dataSource = null;
}
 
Example 14
Source File: DruidDataSourceConfig.java    From xxpay-master with MIT License 5 votes vote down vote up
@Bean(initMethod = "init", destroyMethod = "close")
public DruidDataSource dataSource() throws SQLException {
    if (StringUtils.isEmpty(propertyResolver.getProperty("url"))) {
        System.out.println("Your database connection pool configuration is incorrect!"
                + " Please check your Spring profile, current profiles are:"
                + Arrays.toString(environment.getActiveProfiles()));
        throw new ApplicationContextException(
                "Database connection pool is not configured correctly");
    }
    DruidDataSource druidDataSource = new DruidDataSource();
    druidDataSource.setDriverClassName(propertyResolver.getProperty("driver-class-name"));
    druidDataSource.setUrl(propertyResolver.getProperty("url"));
    druidDataSource.setUsername(propertyResolver.getProperty("username"));
    druidDataSource.setPassword(propertyResolver.getProperty("password"));
    druidDataSource.setInitialSize(Integer.parseInt(propertyResolver.getProperty("initialSize")));
    druidDataSource.setMinIdle(Integer.parseInt(propertyResolver.getProperty("minIdle")));
    druidDataSource.setMaxActive(Integer.parseInt(propertyResolver.getProperty("maxActive")));
    druidDataSource.setMaxWait(Integer.parseInt(propertyResolver.getProperty("maxWait")));
    druidDataSource.setTimeBetweenEvictionRunsMillis(Long.parseLong(propertyResolver.getProperty("timeBetweenEvictionRunsMillis")));
    druidDataSource.setMinEvictableIdleTimeMillis(Long.parseLong(propertyResolver.getProperty("minEvictableIdleTimeMillis")));
    druidDataSource.setValidationQuery(propertyResolver.getProperty("validationQuery"));
    druidDataSource.setTestWhileIdle(Boolean.parseBoolean(propertyResolver.getProperty("testWhileIdle")));
    druidDataSource.setTestOnBorrow(Boolean.parseBoolean(propertyResolver.getProperty("testOnBorrow")));
    druidDataSource.setTestOnReturn(Boolean.parseBoolean(propertyResolver.getProperty("testOnReturn")));
    druidDataSource.setPoolPreparedStatements(Boolean.parseBoolean(propertyResolver.getProperty("poolPreparedStatements")));
    druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(Integer.parseInt(propertyResolver.getProperty("maxPoolPreparedStatementPerConnectionSize")));
    druidDataSource.setFilters(propertyResolver.getProperty("filters"));
    return druidDataSource;
}
 
Example 15
Source File: DruidConfig.java    From mykit-delay with Apache License 2.0 5 votes vote down vote up
public DataSource newInstanceDruidDataSource() throws Exception {
    if (mydataSource != null) {
        return mydataSource;
    }
    DruidDataSource druidDataSource = new DruidDataSource();
    druidDataSource.setUrl(this.url);
    druidDataSource.setUsername(this.username);
    druidDataSource.setPassword(this.password);
    druidDataSource.setDriverClassName(this.driverClassName);
    druidDataSource.setInitialSize(this.initialSize);
    druidDataSource.setMaxActive(this.maxActive);
    druidDataSource.setMinIdle(this.minIdle);
    druidDataSource.setMaxWait(this.maxWait);
    druidDataSource.setTimeBetweenEvictionRunsMillis(this.timeBetweenEvictionRunsMillis);
    druidDataSource.setMinEvictableIdleTimeMillis(this.minEvictableIdleTimeMillis);
    druidDataSource.setValidationQuery(this.validationQuery);
    druidDataSource.setTestWhileIdle(this.testWhileIdle);
    druidDataSource.setTestOnBorrow(this.testOnBorrow);
    druidDataSource.setTestOnReturn(this.testOnReturn);
    druidDataSource.setPoolPreparedStatements(this.poolPreparedStatements);
    druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(this.maxPoolPreparedStatementPerConnectionSize);
    druidDataSource.setFilters(this.filters);

    try {
        if (null != druidDataSource) {
            druidDataSource.setFilters("wall,stat");
            druidDataSource.setUseGlobalDataSourceStat(true);
            druidDataSource.init();
        }
    } catch (Exception e) {
        throw new RuntimeException("load datasource error, dbProperties is :", e);
    }
    synchronized (this) {
        mydataSource = druidDataSource;
    }
    druidDataSource.init();
    return druidDataSource;
}
 
Example 16
Source File: DruidSample.java    From tddl5 with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    DruidDataSource ds = new DruidDataSource();
    ds.setUrl("jdbc:mysql://127.0.0.1:9507/");
    ds.setUsername("TDDL5_APP");
    ds.setPassword("TDDL5_APP");
    ds.init();

    System.out.println("init done");
    Connection conn = ds.getConnection();
    // insert a record
    // conn.prepareStatement("replace into sample_table (id,name,address) values (1,'sun','hz')").executeUpdate();
    System.out.println("insert done");
    // select all records
    PreparedStatement ps = conn.prepareStatement("replace into tddl_category (id,name,gmt_modified,gmt_create) values (1,'aa',now(),now())");
    // ps.executeUpdate();

    ps = conn.prepareStatement("show @@version");
    // ps.setDate(1, new Date(System.currentTimeMillis()));
    ResultSet rs = ps.executeQuery();
    while (rs.next()) {
        StringBuilder sb = new StringBuilder();
        int count = rs.getMetaData().getColumnCount();
        for (int i = 1; i <= count; i++) {
            String key = rs.getMetaData().getColumnLabel(i);
            Object val = rs.getObject(i);
            sb.append("[" + rs.getMetaData().getTableName(i) + "." + key + "->" + val + "]");
        }
        System.out.println(sb.toString());
    }

    rs.close();
    ps.close();
    conn.close();
    System.out.println("query done");
}
 
Example 17
Source File: AdapterCanalConfig.java    From canal-1.1.3 with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("resource")
public void setSrcDataSources(Map<String, DatasourceConfig> srcDataSources) {
    this.srcDataSources = srcDataSources;

    if (srcDataSources != null) {
        for (Map.Entry<String, DatasourceConfig> entry : srcDataSources.entrySet()) {
            DatasourceConfig datasourceConfig = entry.getValue();
            // 加载数据源连接池
            DruidDataSource ds = new DruidDataSource();
            ds.setDriverClassName(datasourceConfig.getDriver());
            ds.setUrl(datasourceConfig.getUrl());
            ds.setUsername(datasourceConfig.getUsername());
            ds.setPassword(datasourceConfig.getPassword());
            ds.setInitialSize(1);
            ds.setMinIdle(1);
            ds.setMaxActive(datasourceConfig.getMaxActive());
            ds.setMaxWait(60000);
            ds.setTimeBetweenEvictionRunsMillis(60000);
            ds.setMinEvictableIdleTimeMillis(300000);
            ds.setValidationQuery("select 1");
            try {
                ds.init();
            } catch (SQLException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
            DatasourceConfig.DATA_SOURCES.put(entry.getKey(), ds);
        }
    }
}
 
Example 18
Source File: DruidProperties.java    From SpringBootBucket with MIT License 5 votes vote down vote up
public void config(DruidDataSource dataSource) {
    dataSource.setDbType(JdbcConstants.MYSQL);
    dataSource.setUrl(url);
    dataSource.setUsername(username);
    dataSource.setPassword(password);
    dataSource.setDriverClassName(driverClassName);
    dataSource.setInitialSize(initialSize);     // 定义初始连接数
    dataSource.setMinIdle(minIdle);             // 最小空闲
    dataSource.setMaxActive(maxActive);         // 定义最大连接数
    dataSource.setMaxWait(maxWait);             // 获取连接等待超时的时间
    dataSource.setRemoveAbandoned(removeAbandoned); // 超过时间限制是否回收
    dataSource.setRemoveAbandonedTimeout(removeAbandonedTimeout); // 超过时间限制多长

    // 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
    dataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
    // 配置一个连接在池中最小生存的时间,单位是毫秒
    dataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
    // 用来检测连接是否有效的sql,要求是一个查询语句
    dataSource.setValidationQuery(validationQuery);
    // 申请连接的时候检测
    dataSource.setTestWhileIdle(testWhileIdle);
    // 申请连接时执行validationQuery检测连接是否有效,配置为true会降低性能
    dataSource.setTestOnBorrow(testOnBorrow);
    // 归还连接时执行validationQuery检测连接是否有效,配置为true会降低性能
    dataSource.setTestOnReturn(testOnReturn);
    // 打开PSCache,并且指定每个连接上PSCache的大小
    dataSource.setPoolPreparedStatements(poolPreparedStatements);
    dataSource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
    // 属性类型是字符串,通过别名的方式配置扩展插件,常用的插件有:
    // 监控统计用的filter:stat
    // 日志用的filter:log4j
    // 防御SQL注入的filter:wall
    try {
        dataSource.setFilters(filters);
    } catch (SQLException e) {
        e.printStackTrace();
    }
}
 
Example 19
Source File: DruidConfig.java    From codeway_service with GNU General Public License v3.0 5 votes vote down vote up
@Bean     //声明其为Bean实例
@Primary  //在同样的DataSource中,首先使用被标注的DataSource
public DataSource dataSource() {
    DruidDataSource datasource = new DruidDataSource();
    logger.info("dbUrl--------" + dbUrl);
    datasource.setUrl(this.dbUrl);
    datasource.setUsername(username);
    datasource.setPassword(password);
    datasource.setDriverClassName(driverClassName);
    //configuration
    datasource.setInitialSize(initialSize);
    datasource.setMinIdle(minIdle);
    datasource.setMaxActive(maxActive);
    datasource.setMaxWait(maxWait);
    datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
    datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
    datasource.setValidationQuery(validationQuery);
    datasource.setTestWhileIdle(testWhileIdle);
    datasource.setTestOnBorrow(testOnBorrow);
    datasource.setTestOnReturn(testOnReturn);
    datasource.setPoolPreparedStatements(poolPreparedStatements);
    datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
    try {
        datasource.setFilters(filters);
    } catch (SQLException e) {
        logger.error("druid configuration initialization filter", e);
    }
    datasource.setConnectionProperties(connectionProperties);

    return datasource;
}
 
Example 20
Source File: DruidDataSourceConfig.java    From genericdao with Artistic License 2.0 4 votes vote down vote up
/**
 * 构建alibaba的数据库连接池
 * @param environment
 * @param propertyPrefix
 * @return
 */
@Override
public DataSource buildDataSource(Environment environment , String propertyPrefix){
	DruidDataSource dataSource = new DruidDataSource() ;
	
	dataSource.setDriverClassName(environment.getRequiredProperty(propertyPrefix+PROPERTY_NAME_JDBC_DRIVER));
	dataSource.setUrl(environment.getRequiredProperty(propertyPrefix+PROPERTY_NAME_JDBC_URL));
	dataSource.setUsername(environment.getRequiredProperty(propertyPrefix+PROPERTY_NAME_JDBC_USERNAME));
	dataSource.setPassword(environment.getRequiredProperty(propertyPrefix+PROPERTY_NAME_JDBC_PASSWORD));
	
	//分别设置最大和最小连接数
	if(environment.containsProperty(propertyPrefix+PROPERTY_NAME_JDBC_POOL_MAXACTIVE)){
		dataSource.setMaxActive(environment.getProperty(propertyPrefix+PROPERTY_NAME_JDBC_POOL_MAXACTIVE , Integer.class));
	}
	
	if(environment.containsProperty(propertyPrefix+PROPERTY_NAME_JDBC_POOL_MINIDLE)){
		dataSource.setMinIdle(environment.getProperty(propertyPrefix+PROPERTY_NAME_JDBC_POOL_MINIDLE , Integer.class));
	}
	
	dataSource.setDefaultAutoCommit(false);
	
	//是否需要进行验证
	dataSource.setValidationQuery(environment.getRequiredProperty(propertyPrefix+PROPERTY_NAME_VALIDATION_QUERY));
	//由连接池中获取连接时,需要进行验证
	dataSource.setTestOnBorrow(true) ;
	//归还连接时不需要验证
	dataSource.setTestOnReturn(false) ;
	//连接空闲时进行验证
	dataSource.setTestWhileIdle(true) ;

	//设置datasource监控,只对sql执行状态进行监控
	try {
		dataSource.setFilters("stat") ;
	}catch (Exception e){
		e.printStackTrace() ;
	}

	if(StringUtils.isNotBlank(environment.getProperty(propertyPrefix+PROPERTY_NAME_VALIDATION_INTERVAL))){
		//连接有效的验证时间间隔
		dataSource.setValidationQueryTimeout(environment.getRequiredProperty(propertyPrefix+PROPERTY_NAME_VALIDATION_INTERVAL , Integer.class));
		//连接空闲验证的时间间隔
		dataSource.setTimeBetweenEvictionRunsMillis(environment.getRequiredProperty(propertyPrefix+PROPERTY_NAME_VALIDATION_INTERVAL , Long.class));
	}
	
	return dataSource ;
}