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

The following examples show how to use com.alibaba.druid.pool.DruidDataSource#setTestOnBorrow() . 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: DruidDataSourceFactory.java    From journalkeeper with Apache License 2.0 6 votes vote down vote up
@Override
public DataSource createDataSource(Path path, Properties properties) {
    String url = properties.getProperty(DruidConfigs.URL);
    if (StringUtils.isBlank(url)) {
        throw new IllegalArgumentException("url not exist");
    }

    DruidDataSource dataSource = new DruidDataSource();
    dataSource.setUrl(url.replace(JDBCConfigs.DATASOURCE_PATH_PLACEHOLDER, path.toString()));
    dataSource.setDriverClassName(properties.getProperty(DruidConfigs.DRIVER_CLASS));
    dataSource.setUsername(properties.getProperty(DruidConfigs.USERNAME, dataSource.getUsername()));
    dataSource.setPassword(properties.getProperty(DruidConfigs.PASSWORD, dataSource.getPassword()));
    dataSource.setInitialSize(Integer.valueOf(properties.getProperty(DruidConfigs.INITIAL_SIZE, String.valueOf(dataSource.getInitialSize()))));
    dataSource.setMinIdle(Integer.valueOf(properties.getProperty(DruidConfigs.MIN_IDLE, String.valueOf(dataSource.getMinIdle()))));
    dataSource.setMaxActive(Integer.valueOf(properties.getProperty(DruidConfigs.MAX_ACTIVE, String.valueOf(dataSource.getMaxActive()))));
    dataSource.setMaxWait(Integer.valueOf(properties.getProperty(DruidConfigs.MAX_WAIT, String.valueOf(dataSource.getMaxWait()))));
    dataSource.setTimeBetweenEvictionRunsMillis(Integer.valueOf(properties.getProperty(DruidConfigs.TIME_BETWEEN_EVICTION_RUNS_MILLIS,
            String.valueOf(dataSource.getTimeBetweenEvictionRunsMillis()))));
    dataSource.setValidationQuery(properties.getProperty(DruidConfigs.VALIDATION_QUERY, DruidConfigs.DEFAULT_VALIDATION_QUERY));
    dataSource.setTestWhileIdle(Boolean.valueOf(properties.getProperty(DruidConfigs.TEST_WHILE_IDLE, String.valueOf(dataSource.isTestWhileIdle()))));
    dataSource.setTestOnBorrow(Boolean.valueOf(properties.getProperty(DruidConfigs.TEST_ONBORROW, String.valueOf(dataSource.isTestOnBorrow()))));
    return dataSource;
}
 
Example 2
Source File: DynamicDataSource.java    From galaxy with Apache License 2.0 6 votes vote down vote up
private DataSource getDruidDataSource(DataSourceInfoDto dto) {
    DruidDataSource druidDataSource = new DruidDataSource();
    druidDataSource.setUrl(dto.getDbUrl());
    druidDataSource.setUsername(dto.getUsername());
    druidDataSource.setPassword(getPassword(dto.getUsername(), dto.getPassword()));
    druidDataSource.setMaxActive(dto.getMaxActive());
    druidDataSource.setInitialSize(dto.getInitialSize());
    druidDataSource.setMaxWait(60000);
    druidDataSource.setTimeBetweenEvictionRunsMillis(300000);
    druidDataSource.setMinEvictableIdleTimeMillis(300000);
    druidDataSource.setValidationQuery("select 1");
    druidDataSource.setTestWhileIdle(true);
    druidDataSource.setTestOnBorrow(false);
    druidDataSource.setTestOnReturn(false);
    druidDataSource.setPoolPreparedStatements(true);
    druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(50);
    try {
        druidDataSource.init();
    } catch (SQLException e) {
        log.error("Can't init druidDataSource from DataSourceInfo:" + dto, e);
    }
    return druidDataSource;
}
 
Example 3
Source File: DataSourceConfig.java    From pampas with Apache License 2.0 5 votes vote down vote up
@Bean
public DataSource dataSource(@Value("${pampas.db.driverClassName}") String driverClassName,
                             @Value("${pampas.db.url}") String url,
                             @Value("${pampas.db.username}") String username,
                             @Value("${pampas.db.password}") String password,
                             @Value("${druid.pool.size.max:200}") int max,
                             @Value("${druid.pool.size.min:1}") int min,
                             @Value("${druid.pool.size.init:1}") int init) {
    DruidDataSource druidDataSource = new DruidDataSource();
    druidDataSource.setDriverClassName(driverClassName);
    druidDataSource.setUrl(url);
    druidDataSource.setUsername(username);
    druidDataSource.setPassword(password);
    druidDataSource.setInitialSize(init);
    druidDataSource.setMaxActive(max);
    druidDataSource.setMinIdle(min);
    druidDataSource.setTestOnBorrow(false);
    druidDataSource.setTestWhileIdle(true);
    druidDataSource.setMinEvictableIdleTimeMillis(300000);
    druidDataSource.setTimeBetweenEvictionRunsMillis(120000);
    druidDataSource.setValidationQuery("select 1");
    try {
        druidDataSource.setFilters("stat,wall");
    } catch (SQLException e) {
        log.error("初始化数据源失败:{}", e);
    }

    return druidDataSource;
}
 
Example 4
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 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: DruidConfig.java    From sophia_scaffolding 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(url);
    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);
    logger.debug("druid configuration datasource 成功"  + datasource);
    logger.debug("druid configuration datasource 成功"  + name);
    return datasource;
}
 
Example 7
Source File: DruidConfig.java    From sophia_scaffolding 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(url);
    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);
    logger.debug("druid configuration datasource 成功"  + datasource);
    logger.debug("druid configuration datasource 成功"  + name);
    return datasource;
}
 
Example 8
Source File: MasterDataSourceConfig.java    From springBoot-study with Apache License 2.0 5 votes vote down vote up
@Bean(name = "masterDataSource")
@Primary //标志这个 Bean 如果在多个同类 Bean 候选时,该 Bean 优先被考虑。
public DataSource masterDataSource() {
    DruidDataSource dataSource = new DruidDataSource();
    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.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) { 
    	e.printStackTrace();
    }  
    dataSource.setConnectionProperties(connectionProperties);  
    return dataSource;
}
 
Example 9
Source File: DataSourceConfiguration.java    From dk-foundation with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static DruidDataSource initDataSource(String url, String username, String password) {
    DruidDataSource druidDataSource = new DruidDataSource();
    druidDataSource.setUrl(url);
    druidDataSource.setUsername(username);
    druidDataSource.setPassword(password);

    try {
        druidDataSource.setFilters("stat");
    } catch (SQLException e) {
        e.printStackTrace();
        logger.error("druid filter init failed",e);
    }

    druidDataSource.setMaxActive(20);
    druidDataSource.setInitialSize(1);
    druidDataSource.setMaxWait(60000);
    druidDataSource.setMinIdle(1);

    druidDataSource.setTimeBetweenEvictionRunsMillis(60000);
    druidDataSource.setMinEvictableIdleTimeMillis(300000);

    druidDataSource.setValidationQuery("select 'x'");
    druidDataSource.setTestWhileIdle(true);
    druidDataSource.setTestOnBorrow(false);
    druidDataSource.setTestOnReturn(false);
    druidDataSource.setPoolPreparedStatements(true);
    druidDataSource.setMaxOpenPreparedStatements(20);
    druidDataSource.setKeepAlive(true);
    druidDataSource.setRemoveAbandoned(true);

    return druidDataSource;
}
 
Example 10
Source File: DruidProperties.java    From LuckyFrameWeb with GNU Affero General Public License v3.0 5 votes vote down vote up
public DruidDataSource dataSource(DruidDataSource datasource)
{
    // 配置初始化大小、最小、最大
    datasource.setInitialSize(initialSize);
    datasource.setMaxActive(maxActive);
    datasource.setMinIdle(minIdle);

    //配置获取连接等待超时的时间
    datasource.setMaxWait(maxWait);

    //配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
    datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);

    // 配置一个连接在池中最小、最大生存的时间,单位是毫秒
    datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
    datasource.setMaxEvictableIdleTimeMillis(maxEvictableIdleTimeMillis);

    //用来检测连接是否有效的sql,要求是一个查询语句,常用select 'x'。如果validationQuery为null,testOnBorrow、testOnReturn、testWhileIdle都不会起作用。
    datasource.setValidationQuery(validationQuery);
    // 建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。
    datasource.setTestWhileIdle(testWhileIdle);
    // 申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。
    datasource.setTestOnBorrow(testOnBorrow);
    //归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。
    datasource.setTestOnReturn(testOnReturn);
    return datasource;
}
 
Example 11
Source File: ClusterDataSourceConfig.java    From springBoot-study with Apache License 2.0 5 votes vote down vote up
@Bean(name = "clusterDataSource")
public DataSource clusterDataSource() {
    DruidDataSource dataSource = new DruidDataSource();
    dataSource.setUrl(url);  
    dataSource.setUsername(username);  
    dataSource.setPassword(password);  
    dataSource.setDriverClassName(driverClass);  
      
    //具体配置 
    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) { 
    	e.printStackTrace();
    }  
    dataSource.setConnectionProperties(connectionProperties);  
    return dataSource;
}
 
Example 12
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 13
Source File: DbConfig.java    From oauth-boot with MIT License 5 votes vote down vote up
/**
* <!-- 配置初始化大小、最小、最大 -->
    <property name="initialSize" value="10" />
    <property name="minIdle" value="30" />
    <property name="maxActive" value="300" />
    <!-- 配置获取连接等待超时的时间 -->
    <property name="maxWait" value="3600000" />
    <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
    <property name="timeBetweenEvictionRunsMillis" value="60000" />
    <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
    <property name="minEvictableIdleTimeMillis" value="30000" />
    <property name="validationQuery" value="SELECT 'x' FROM dual" />
    <property name="testWhileIdle" value="true" />
    <property name="testOnBorrow" value="false" />
    <property name="testOnReturn" value="false" />
    <!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
    <property name="poolPreparedStatements" value="true" />
    <property name="maxPoolPreparedStatementPerConnectionSize"
    value="20" />
*
* */
@Bean
@Primary
public DataSource dataSource() {
    DruidDataSource dr = new DruidDataSource();
    dr.setUsername(this.username);
    dr.setPassword(this.password);
    dr.setDriverClassName(this.driverClassName);
    dr.setUrl(this.url);

    this.logger.info(this.url+":"+this.username+":"+this.password);

    dr.setInitialSize(10);
    dr.setMinIdle(30);
    dr.setMaxActive(300);
    dr.setMaxWait(3600000);
    dr.setTimeBetweenEvictionRunsMillis(60000);
    dr.setMinEvictableIdleTimeMillis(30000);
    dr.setValidationQuery("select 'X' from dual");
    dr.setTestWhileIdle(true);
    dr.setTestOnBorrow(false);
    dr.setTestOnReturn(false);
    dr.setPoolPreparedStatements(true);
    dr.setMaxPoolPreparedStatementPerConnectionSize(20);

    return dr;
}
 
Example 14
Source File: RehashLauncher.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
private void initDataSource(){
	dataSource=new DruidDataSource();
	dataSource.setAsyncCloseConnectionEnable(true);
	dataSource.setBreakAfterAcquireFailure(true);
	dataSource.setDefaultAutoCommit(true);
	dataSource.setDefaultReadOnly(true);
	dataSource.setDriverClassName(args.getJdbcDriver());
	dataSource.setEnable(true);
	dataSource.setPassword(args.getPassword());
	dataSource.setTestOnBorrow(true);
	dataSource.setTestOnReturn(true);
	dataSource.setTestWhileIdle(true);
	dataSource.setUrl(args.getJdbcUrl());
	dataSource.setUsername(args.getUser());
}
 
Example 15
Source File: DruidConfig.java    From Photo with GNU General Public License v3.0 5 votes vote down vote up
@Bean // 声明其为Bean实例
@Primary // 在同样的DataSource中,首先使用被标注的DataSource
public DataSource dataSource() throws SQLException {
	DruidDataSource datasource = new DruidDataSource();

	datasource.setUrl(this.url);
	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);

	datasource.setFilters(filters);

	return datasource;
}
 
Example 16
Source File: DruidConfig.java    From renren-fast with GNU General Public License v3.0 4 votes vote down vote up
@Bean
@Primary
public DataSource dataSource(){
    DruidDataSource datasource = new DruidDataSource();

    datasource.setUrl(this.dbUrl);
    datasource.setUsername(username);
    datasource.setPassword(password);
    datasource.setDriverClassName(driverClassName);
    //configuration
    if(initialSize != null) {
        datasource.setInitialSize(initialSize);
    }
    if(minIdle != null) {
        datasource.setMinIdle(minIdle);
    }
    if(maxActive != null) {
        datasource.setMaxActive(maxActive);
    }
    if(maxWait != null) {
        datasource.setMaxWait(maxWait);
    }
    if(timeBetweenEvictionRunsMillis != null) {
        datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
    }
    if(minEvictableIdleTimeMillis != null) {
        datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
    }
    if(validationQuery!=null) {
        datasource.setValidationQuery(validationQuery);
    }
    if(testWhileIdle != null) {
        datasource.setTestWhileIdle(testWhileIdle);
    }
    if(testOnBorrow != null) {
        datasource.setTestOnBorrow(testOnBorrow);
    }
    if(testOnReturn != null) {
        datasource.setTestOnReturn(testOnReturn);
    }
    if(poolPreparedStatements != null) {
        datasource.setPoolPreparedStatements(poolPreparedStatements);
    }
    if(maxPoolPreparedStatementPerConnectionSize != null) {
        datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
    }

    if(connectionProperties != null) {
        datasource.setConnectionProperties(connectionProperties);
    }

    List<Filter> filters = new ArrayList<>();
    filters.add(statFilter());
    filters.add(wallFilter());
    datasource.setProxyFilters(filters);

    return datasource;
}
 
Example 17
Source File: DruidDataSourcePool.java    From Zebra with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
@Override
public DataSource build(DataSourceConfig config, boolean withDefaultValue) {
	DruidDataSource druidDataSource = new DruidDataSource();

	druidDataSource.setName(buildDsName(config));
	druidDataSource.setUrl(config.getJdbcUrl());
	druidDataSource.setUsername(config.getUsername());
	druidDataSource.setPassword(config.getPassword());
	druidDataSource.setDriverClassName(StringUtils.isNotBlank(config.getDriverClass()) ? config.getDriverClass()
	      : JdbcDriverClassHelper.getDriverClassNameByJdbcUrl(config.getJdbcUrl()));

	if (withDefaultValue) {
		druidDataSource.setInitialSize(getIntProperty(config, "initialPoolSize", 5));
		druidDataSource.setMaxActive(getIntProperty(config, "maxPoolSize", 30));
		druidDataSource.setMinIdle(getIntProperty(config, "minPoolSize", 5));
		druidDataSource.setMaxWait(getIntProperty(config, "checkoutTimeout", 1000));
		druidDataSource.setValidationQuery(getStringProperty(config, "preferredTestQuery", "SELECT 1"));
		druidDataSource.setMinEvictableIdleTimeMillis(getIntProperty(config, "minEvictableIdleTimeMillis", 1800000));// 30min
		druidDataSource
		      .setTimeBetweenEvictionRunsMillis(getIntProperty(config, "timeBetweenEvictionRunsMillis", 30000)); // 30s
		druidDataSource.setNumTestsPerEvictionRun(getIntProperty(config, "numTestsPerEvictionRun", 6));
		druidDataSource.setValidationQueryTimeout(getIntProperty(config, "validationQueryTimeout", 0));
		druidDataSource.setRemoveAbandonedTimeout(getIntProperty(config, "removeAbandonedTimeout", 300));
		if (StringUtils.isNotBlank(getStringProperty(config, "connectionInitSql", null))) {
			List<String> initSqls = new ArrayList<String>();
			initSqls.add(getStringProperty(config, "connectionInitSql", null));
			druidDataSource.setConnectionInitSqls(initSqls);
		}

		druidDataSource.setTestWhileIdle(true);
		druidDataSource.setTestOnBorrow(false);
		druidDataSource.setTestOnReturn(false);
		druidDataSource.setRemoveAbandoned(true);
		druidDataSource.setUseUnfairLock(true);
		druidDataSource.setNotFullTimeoutRetryCount(-1);
	} else {
		try {
			PropertiesInit<DruidDataSource> propertiesInit = new PropertiesInit<DruidDataSource>(druidDataSource);
			propertiesInit.initPoolProperties(config);
		} catch (Exception e) {
			throw new ZebraConfigException(String.format("druid dataSource [%s] created error : ", config.getId()), e);
		}
	}

	this.pool = druidDataSource;
	LOGGER.info(String.format("New dataSource [%s] created.", config.getId()));

	return this.pool;
}
 
Example 18
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 19
Source File: DataDruidFactory.java    From DataSphereStudio with Apache License 2.0 4 votes vote down vote up
private static DruidDataSource createDataSource(Properties props, Logger log, String type) {
		String name = null;
		String url = null;
		String username = null;
		String password = null;
		
		if (type.equals("Job")) {
			name = props.getProperty("job.datachecker.jdo.option.name");
			url = props.getProperty("job.datachecker.jdo.option.url");
			username = props.getProperty("job.datachecker.jdo.option.username");
			password = props.getProperty("job.datachecker.jdo.option.password");
			try {
//				password = new String(Base64.getDecoder().decode(props.getProperty("job.datachecker.jdo.option.password").getBytes()),"UTF-8");
				password = props.getProperty("job.datachecker.jdo.option.password");
			} catch (Exception e){
				log.error("password decore failed" + e);
			}
		}
		int initialSize = Integer.valueOf(props.getProperty("datachecker.jdo.option.initial.size", "1"));
		int maxActive = Integer.valueOf(props.getProperty("datachecker.jdo.option.max.active", "100"));
		int minIdle = Integer.valueOf(props.getProperty("datachecker.jdo.option.min.idle", "1"));
		long maxWait = Long.valueOf(props.getProperty("datachecker.jdo.option.max.wait", "60000"));
		String validationQuery = props.getProperty("datachecker.jdo.option.validation.quert", "SELECT 'x'");
		long timeBetweenEvictionRunsMillis = Long.valueOf(props.getProperty("datachecker.jdo.option.time.between.eviction.runs.millis", "6000"));
		long minEvictableIdleTimeMillis = Long.valueOf(props.getProperty("datachecker.jdo.option.evictable.idle,time.millis", "300000"));
		boolean testOnBorrow = Boolean.valueOf(props.getProperty("datachecker.jdo.option.test.on.borrow", "true"));
		int maxOpenPreparedStatements = Integer.valueOf(props.getProperty("datachecker.jdo.option.max.open.prepared.statements", "-1"));
		
		
		if (timeBetweenEvictionRunsMillis > minEvictableIdleTimeMillis) {
			timeBetweenEvictionRunsMillis = minEvictableIdleTimeMillis;
		}
		
		DruidDataSource ds = new DruidDataSource();
		
		if (StringUtils.isNotBlank(name)) {
			ds.setName(name);
		}
		
		ds.setUrl(url);
		ds.setDriverClassName("com.mysql.jdbc.Driver");
	    ds.setUsername(username);
	    ds.setPassword(password);
	    ds.setInitialSize(initialSize);
	    ds.setMinIdle(minIdle);
	    ds.setMaxActive(maxActive);
	    ds.setMaxWait(maxWait);
	    ds.setTestOnBorrow(testOnBorrow);
	    ds.setValidationQuery(validationQuery);
	    ds.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
	    ds.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
	    if (maxOpenPreparedStatements > 0) {
	      ds.setPoolPreparedStatements(true);
	      ds.setMaxPoolPreparedStatementPerConnectionSize(
	          maxOpenPreparedStatements);
	    } else {
	      ds.setPoolPreparedStatements(false);
	    }
	    log.info("Druid data source initialed!");
	    return ds;
	}
 
Example 20
Source File: EventDruidFactory.java    From DataSphereStudio with Apache License 2.0 4 votes vote down vote up
private static DruidDataSource createDataSource(Properties props, Logger log, String type) {
		String name = null;
		String url = null;
		String username = null;
		String password = null;
		
		if(type.equals("Msg")){
			name = props.getProperty("msg.eventchecker.jdo.option.name");
			url = props.getProperty("msg.eventchecker.jdo.option.url");
			username = props.getProperty("msg.eventchecker.jdo.option.username");
			try {
//				password = new String(Base64.getDecoder().decode(props.getProperty("msg.eventchecker.jdo.option.password").getBytes()),"UTF-8");
				password = props.getProperty("msg.eventchecker.jdo.option.password");
			} catch (Exception e){
				log.error("password decore failed" + e);
			}
		}
		
		int initialSize = Integer.valueOf(props.getProperty("option.initial.size", "1"));
		int maxActive = Integer.valueOf(props.getProperty("option.max.active", "100"));
		int minIdle = Integer.valueOf(props.getProperty("option.min.idle", "1"));
		long maxWait = Long.valueOf(props.getProperty("option.max.wait", "60000"));
		String validationQuery = props.getProperty("option.validation.quert", "SELECT 'x'");
		long timeBetweenEvictionRunsMillis = Long.valueOf(props.getProperty("option.time.between.eviction.runs.millis", "6000"));
		long minEvictableIdleTimeMillis = Long.valueOf(props.getProperty("option.evictable.idle,time.millis", "300000"));
		boolean testOnBorrow = Boolean.valueOf(props.getProperty("option.test.on.borrow", "true"));
		int maxOpenPreparedStatements = Integer.valueOf(props.getProperty("option.max.open.prepared.statements", "-1"));

		if (timeBetweenEvictionRunsMillis > minEvictableIdleTimeMillis) {
			timeBetweenEvictionRunsMillis = minEvictableIdleTimeMillis;
		}
		
		DruidDataSource ds = new DruidDataSource();
		
		if (StringUtils.isNotBlank(name)) {
			ds.setName(name);
		}
		
		ds.setUrl(url);
		ds.setDriverClassName("com.mysql.jdbc.Driver");
	    ds.setUsername(username);
	    ds.setPassword(password);
	    ds.setInitialSize(initialSize);
	    ds.setMinIdle(minIdle);
	    ds.setMaxActive(maxActive);
	    ds.setMaxWait(maxWait);
	    ds.setTestOnBorrow(testOnBorrow);
	    ds.setValidationQuery(validationQuery);
	    ds.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
	    ds.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
	    if (maxOpenPreparedStatements > 0) {
	      ds.setPoolPreparedStatements(true);
	      ds.setMaxPoolPreparedStatementPerConnectionSize(
	          maxOpenPreparedStatements);
	    } else {
	      ds.setPoolPreparedStatements(false);
	    }
	    log.info("Druid data source initialed!");
	    return ds;
	}