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

The following examples show how to use com.alibaba.druid.pool.DruidDataSource#setMinIdle() . 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: DbRemoteConfigLoader.java    From canal-1.1.3 with Apache License 2.0 6 votes vote down vote up
public DbRemoteConfigLoader(String driverName, String jdbcUrl, String jdbcUsername, String jdbcPassword){
    dataSource = new DruidDataSource();
    if (StringUtils.isEmpty(driverName)) {
        driverName = "com.mysql.jdbc.Driver";
    }
    dataSource.setDriverClassName(driverName);
    dataSource.setUrl(jdbcUrl);
    dataSource.setUsername(jdbcUsername);
    dataSource.setPassword(jdbcPassword);
    dataSource.setInitialSize(1);
    dataSource.setMinIdle(1);
    dataSource.setMaxActive(1);
    dataSource.setMaxWait(60000);
    dataSource.setTimeBetweenEvictionRunsMillis(60000);
    dataSource.setMinEvictableIdleTimeMillis(300000);
    try {
        dataSource.init();
    } catch (SQLException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}
 
Example 2
Source File: ActivitiConfig.java    From easyweb with Apache License 2.0 6 votes vote down vote up
@Bean(name = "activitidatabaseSource")
public DataSource dataSource() {
    DruidDataSource datasource = new DruidDataSource();
    datasource.setUrl(databaseConfig.getUrl());
    datasource.setDriverClassName(databaseConfig.getDriverClassName());
    datasource.setUsername(databaseConfig.getUsername());
    datasource.setPassword(databaseConfig.getPassword());
    datasource.setInitialSize(databaseConfig.getInitialSize());
    datasource.setMinIdle(databaseConfig.getMinIdle());
    datasource.setMaxWait(databaseConfig.getMaxWait());
    datasource.setMaxActive(databaseConfig.getMaxActive());
    datasource.setMinEvictableIdleTimeMillis(databaseConfig.getMinEvictableIdleTimeMillis());
    try {
        datasource.setFilters("stat,wall,log4j2");
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return datasource;
}
 
Example 3
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 4
Source File: DataSourceCreator.java    From tddl5 with Apache License 2.0 6 votes vote down vote up
@Override
public DataSource createDataSource(String ip, int port, String user, String password) {

    DruidDataSource ds = new DruidDataSource();
    ds.setUsername(user);
    ds.setPassword(password);
    ds.setUrl(new StringBuilder().append("jdbc:mysql://")
        .append(ip)
        .append(":")
        .append(port)
        .append("/")
        .toString());
    ds.setDriverClassName(driverClassName);
    ds.setMaxActive(maxActive);
    ds.setMinIdle(minIdle);
    ds.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
    // ds.setNumTestsPerEvictionRun(numTestsPerEvictionRun);
    ds.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);

    return ds;
}
 
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: AdapterCanalConfig.java    From canal 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 7
Source File: DatabaseConfiguration.java    From huanhuan-blog with Apache License 2.0 5 votes vote down vote up
/**
 * 数据库连接配置
 */
@Bean(initMethod = "init", destroyMethod = "close")
public DataSource dataSource() {
    logger.debug("Configuring Datasource");

    DruidDataSource druidDataSource = new DruidDataSource();
    druidDataSource.setDriverClassName(driverClassName);
    druidDataSource.setUrl(url);
    druidDataSource.setUsername(username);
    druidDataSource.setPassword(password);
    druidDataSource.setMaxActive(maximumPoolSize);
    druidDataSource.setMaxWait(60000);
    druidDataSource.setMinIdle(1);
    druidDataSource.setValidationQuery("SELECT 1");
    druidDataSource.setTestWhileIdle(true);
    druidDataSource.setTestOnBorrow(false);
    druidDataSource.setTestOnReturn(false);
    /**
     * configuration exception handling
     * */
    druidDataSource.setQueryTimeout(15); //查询超时时间15s
    //通过datasource.getConnontion() 取得的连接必须在removeAbandonedTimeout这么多秒内调用close(),要不强制关闭.(就是conn不能超过指定的租期)
    druidDataSource.setRemoveAbandoned(true);
    druidDataSource.setRemoveAbandonedTimeout(600); //一个连接的租期10分钟,超时会被强制关闭
    druidDataSource.setLogAbandoned(true);
    return druidDataSource;
}
 
Example 8
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 9
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 10
Source File: DbNodeServiceImpl.java    From pmq with Apache License 2.0 5 votes vote down vote up
protected void checkSlave(DbNodeEntity dbNodeEntity) throws SQLException {
	// 检查slave
	if (hasSlave(dbNodeEntity)) {
		DruidDataSource dataSource = dataSourceFactory.createDataSource();
		dataSource.setDriverClassName("com.mysql.jdbc.Driver");
		dataSource.setUsername(dbNodeEntity.getDbUserNameBak());
		dataSource.setPassword(dbNodeEntity.getDbPassBak());
		dataSource.setUrl(getCon(dbNodeEntity, false));
		dataSource.setInitialSize(1);
		dataSource.setMinIdle(0);
		dataSource.setMaxActive(1);
		dataSource.init();
		dataSource = null;
	}
}
 
Example 11
Source File: EsPublisher.java    From tunnel with Apache License 2.0 5 votes vote down vote up
private DruidDataSource createDataSource(InvokeContext ctx) {
    DruidDataSource dataSource = new DruidDataSource();
    dataSource.setUsername(ctx.getJdbcUser());
    dataSource.setUrl(ctx.getJdbcUrl());
    dataSource.setPassword(ctx.getJdbcPass());
    dataSource.setValidationQuery("select 1");
    dataSource.setMinIdle(20);
    dataSource.setMaxActive(50);
    return dataSource;
}
 
Example 12
Source File: DruidDataSourceConfigurer.java    From FlyCms with MIT License 5 votes vote down vote up
@Bean
public DataSource getDataSource() {
    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) {
        logger.error("druid configuration initialization filter", e);
    }
    datasource.setConnectionProperties(connectionProperties);

    return datasource;
}
 
Example 13
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 14
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 15
Source File: EsPublisher.java    From tunnel with Apache License 2.0 5 votes vote down vote up
private DruidDataSource createDataSource(InvokeContext ctx) {
    DruidDataSource dataSource = new DruidDataSource();
    dataSource.setUsername(ctx.getJdbcUser());
    dataSource.setUrl(ctx.getJdbcUrl());
    dataSource.setPassword(ctx.getJdbcPass());
    dataSource.setValidationQuery("select 1");
    dataSource.setMinIdle(20);
    dataSource.setMaxActive(50);
    return dataSource;
}
 
Example 16
Source File: DruidConfig.java    From dubbo-spring-boot-learning with MIT License 5 votes vote down vote up
@Bean
@Primary
public DataSource dataSource() {
    DruidDataSource datasource = new DruidDataSource();
    datasource.setUrl(dbUrl);
    datasource.setUsername(username);
    datasource.setPassword(password);
    datasource.setDriverClassName(driverClassName);
    datasource.setInitialSize(initialSize);
    datasource.setMinIdle(minIdle);
    datasource.setMaxActive(maxActive);
    return datasource;
}
 
Example 17
Source File: DruidProperties.java    From supplierShop with MIT License 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 18
Source File: MasterDataSourceConfig.java    From springBoot-study with Apache License 2.0 4 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.setPassword("23654");  
        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) { 
        	logger.error(e.getMessage());
        }  
        dataSource.setConnectionProperties(connectionProperties);  
        String password2=AESUtil.decrypt(password);
        //如果为空,说明解密失败,那么就直接连接,若还是失败,说明密码错误,直接退出程序
        dataSource.setPassword(password2==null?password:password2);
    	//如果连接失败,则直接退出程序!
    	if(!testCon(dataSource)){
    		logger.error("数据库连接失败!程序退出!");
    		System.exit(1);
    	}
    	//连接成功并且是明文的话,就直接回写密文
    	if(password2==null){
	    	SetSystemProperty ssp = new SetSystemProperty();
	    	Map<String, String> map = new HashMap<String, String>();
	    	map.put("spring.datasource.password", AESUtil.encrypt(password));
			ssp.updateProperties("application.properties", map, "password Encode");
			logger.error("密文回写成功!");
    	}
        return dataSource;
    }
 
Example 19
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;
	}
 
Example 20
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();
}