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

The following examples show how to use com.alibaba.druid.pool.DruidDataSource#setUrl() . 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: 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 2
Source File: DruidStatTest.java    From metrics with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    TabularData sqlList = JdbcStatManager.getInstance().getSqlList();
    if (sqlList.size() > 0) {
        for (Object item : JdbcStatManager.getInstance().getSqlList().values()) {
            String text = JSONUtils.toJSONString(item);
            System.out.println(text);
        }
    }

    Assert.assertEquals(0, JdbcStatManager.getInstance().getSqlList().size());

    dataSource = new DruidDataSource();
    dataSource.setUrl("jdbc:mock:xx");
    dataSource.setFilters("mergeStat");
    dataSource.setDbType("mysql");
}
 
Example 3
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 4
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 5
Source File: DataSourceConfiguration.java    From mywx with Apache License 2.0 6 votes vote down vote up
/**
 * 初始化数据源
 *
 * @return
 * @throws SQLException
 */

@Bean(destroyMethod = "close")
public DruidDataSource druidDataSource(DataSourceProperties dataSourceProperties) throws SQLException {
    DruidDataSource source = new DruidDataSource();
    source.setUsername(dataSourceProperties.getUserName());
    source.setPassword(dataSourceProperties.getPassWord());
    source.setUrl(dataSourceProperties.getUrl());
    source.setDriverClassName(dataSourceProperties.getDriverClassName());
    source.setFilters(dataSourceProperties.getFilters());
    source.setMaxActive(dataSourceProperties.getMaxActive());
    source.setInitialSize(dataSourceProperties.getInitialSize());
    source.setMinIdle(dataSourceProperties.getMinIdle());
    source.setTimeBetweenEvictionRunsMillis(dataSourceProperties.getTimeBetweenEvictionRunsMillis());
    source.setMinEvictableIdleTimeMillis(dataSourceProperties.getMinEvictableIdleTimeMillis());
    source.setValidationQuery(dataSourceProperties.getValidationQuery());
    source.setTestWhileIdle(dataSourceProperties.isTestWhileIdle());
    source.setTestOnReturn(dataSourceProperties.isTestOnReturn());
    source.setTestOnBorrow(dataSourceProperties.isTestOnBorrow());
    source.setMaxOpenPreparedStatements(dataSourceProperties.getMaxOpenPreparedStatements());
    source.setRemoveAbandoned(dataSourceProperties.isRemoveAbandoned());
    source.setRemoveAbandonedTimeout(dataSourceProperties.getRemoveAbandonedTimeout());
    source.setLogAbandoned(dataSourceProperties.isLogAbandoned());
    return source;
}
 
Example 6
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 7
Source File: CouponApplication.java    From EasyTransaction with Apache License 2.0 5 votes vote down vote up
@Bean
public DataSource dataSourceProxy() {
    
    DruidDataSource druidDataSource = new DruidDataSource();
    druidDataSource.setUrl("jdbc:mysql://localhost:3306/coupon?characterEncoding=UTF-8&useSSL=false");
    druidDataSource.setUsername("root");
    druidDataSource.setPassword("123456");
    
    return new DataSourceProxy(druidDataSource);
}
 
Example 8
Source File: MySQLDruidDataSourceConfiguration.java    From spring-boot with Apache License 2.0 5 votes vote down vote up
@Bean
    @Primary
    public DataSource dataSource() {
        // 数据库驱动配置信息
        DruidDataSource datasource = new DruidDataSource();
        datasource.setDbType(properties.getType());
        datasource.setUrl(properties.getUrl());
        datasource.setUsername(properties.getUsername());
        datasource.setPassword(properties.getPassword());
        datasource.setDriverClassName(properties.getDriver());

        // 数据库连接池配置信息
        datasource.setMaxWait(properties.getMaxWait());
//        datasource.setInitialSize(properties.getInitialSize());  //配置后, junit将不能执行
        datasource.setMinIdle(properties.getMinIdle());
        datasource.setMaxActive(properties.getMaxActive());
        datasource.setMaxWait(properties.getMaxWait());
        datasource.setTimeBetweenEvictionRunsMillis(properties.getTimeBetweenEvictionRunsMillis());
        datasource.setMinEvictableIdleTimeMillis(properties.getMinEvictableIdleTimeMillis());
        datasource.setMaxEvictableIdleTimeMillis(properties.getMaxEvictableIdleTimeMillis());
        datasource.setRemoveAbandoned(properties.isRemoveAbandoned());
        datasource.setRemoveAbandonedTimeoutMillis(properties.getRemoveAbandonedTimeoutMillis());
        datasource.setTimeBetweenConnectErrorMillis(properties.getTimeBetweenConnectErrorMillis());
        datasource.setValidationQuery(properties.getValidationQuery());
        datasource.setTestWhileIdle(properties.isTestWhileIdle());
        datasource.setTestOnBorrow(properties.isTestOnBorrow());
        datasource.setTestOnReturn(properties.isTestOnReturn());
        datasource.setPoolPreparedStatements(properties.isPoolPreparedStatements());
        datasource.setMaxOpenPreparedStatements(properties.getMaxOpenPreparedStatements());
        datasource.setMaxPoolPreparedStatementPerConnectionSize(properties.getMaxPoolPreparedStatementPerConnectionSize());
        datasource.setLogAbandoned(properties.isLogAbandoned());
        try {
            datasource.setFilters(properties.getFilters());
        } catch (SQLException e) {
            log.error("Druid setting filters exception: " + e.getMessage(), e);
        }
        datasource.setConnectionProperties(properties.getConnectionProperties());
        log.info("\n*** Initialize MySQL Druid datasource successful." + properties.getUrl());
        return datasource;
    }
 
Example 9
Source File: DbConfig.java    From sanshanblog with Apache License 2.0 5 votes vote down vote up
@Bean(initMethod = "init", destroyMethod = "close",name = "datasource")
    public DruidDataSource dataSource() throws SQLException {
        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName(driver);
        ds.setUrl(url);
        ds.setUsername(username);
        ds.setPassword(passowrd);
//        最大并发连接数
        ds.setMaxActive(maxActive);
//        初始化连接数量
        ds.setInitialSize(initialSize);
//        配置获取连接等待超时的时间
        ds.setMaxWait(maxWait);
//       最小空闲连接数
        ds.setMinIdle(minIdle);
//        配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
        ds.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
//       配置一个连接在池中最小生存的时间,单位是毫秒
        ds.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
        ds.setValidationQuery("SELECT 1");
        ds.setTestWhileIdle(testWhileIdle);
        //开启mysql的自动事务
        ds.setDefaultAutoCommit(true);
        ds.setTestOnBorrow(testOnBorrow);
        ds.setTestOnReturn(testOnReturn);
        ds.setMaxOpenPreparedStatements(maxOpenPreparedStatements);
        ds.setFilters(filters);
//       打开removeAbandoned功能
        ds.setRemoveAbandoned(removeAbandoned);
//       1800秒,也就是30分钟
        ds.setRemoveAbandonedTimeout(removeAbandonedTimeout);
//       关闭abanded连接时输出错误日志
        ds.setLogAbandoned(logAbandoned);
        return ds;
    }
 
Example 10
Source File: DruidProperties.java    From MeetingFilm with Apache License 2.0 5 votes vote down vote up
public void config(DruidDataSource dataSource) {

        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);

        // 打开PSCache,并且指定每个连接上PSCache的大小
        dataSource.setPoolPreparedStatements(poolPreparedStatements);
        dataSource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);

        try {
            dataSource.setFilters(filters);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
 
Example 11
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 12
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 13
Source File: DruidProvider.java    From tastjava with MIT License 5 votes vote down vote up
@Override
public boolean register() {
    if (IsRegistered) {
        return HAS_REGISTERED;
    }

    DruidDataSource ds = new DruidDataSource();

    if (!StrUtil.isBlank(name)) {
        ds.setName(this.name);
    }

    ds.setUrl(jdbcURL);
    ds.setDriverClassName(jdbcDriver);
    ds.setUsername(jdbcUsername);
    ds.setPassword(jdbcPassword);

    ds.setMinIdle(minIdle);
    ds.setMaxActive(maxActive);
    ds.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
    ds.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
    ds.setValidationQuery(validationQuery);

    ds.setTestWhileIdle(testWhileIdle);
    ds.setTestOnBorrow(testOnBorrow);
    ds.setTestOnReturn(testOnReturn);

    setDataSource(ds);
    setIsRegistered(HAS_REGISTERED);
    return HAS_REGISTERED;
}
 
Example 14
Source File: DataSourceProperties.java    From spring-cloud with Apache License 2.0 5 votes vote down vote up
@Bean
@Primary
public DataSource getDataSource() {
    DruidDataSource dataSource = new DruidDataSource();
    dataSource.setUrl(url);
    dataSource.setUsername(username);
    dataSource.setPassword(password);
    return dataSource;
}
 
Example 15
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 16
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 17
Source File: DruidProperties.java    From spring-boot-starter-dao with Apache License 2.0 4 votes vote down vote up
public DruidDataSource createDataSource() throws SQLException {
	DruidDataSource dataSource = new DruidDataSource();
	dataSource.setUrl(url);
	dataSource.setUsername(username);
	dataSource.setPassword(password);
	dataSource.setDriverClassName(driverClassName);
	dataSource.setConnectProperties(connectProperties);
	dataSource.setInitialSize(initialSize);
	dataSource.setMinIdle(minIdle);
	dataSource.setMaxActive(maxActive);
	dataSource.setMaxWait(maxWait);
	dataSource.setFilters(filters);
	dataSource.setDefaultAutoCommit(defaultAutoCommit);
	dataSource.setTimeBetweenConnectErrorMillis(timeBetweenConnectErrorMillis);
	dataSource.setValidationQuery(validationQuery);
	dataSource.setValidationQueryTimeout(validationQueryTimeout);
	dataSource.setTestWhileIdle(testWhileIdle);
	dataSource.setTestOnBorrow(testOnBorrow);
	dataSource.setTestOnReturn(testOnReturn);
	dataSource.setPoolPreparedStatements(poolPreparedStatements);
	dataSource.setClearFiltersEnable(clearFiltersEnable);
	dataSource.setDefaultReadOnly(defaultReadOnly);
	dataSource.setAsyncCloseConnectionEnable(asyncCloseConnectionEnable);
	dataSource.setConnectionErrorRetryAttempts(connectionErrorRetryAttempts);
	dataSource.setBreakAfterAcquireFailure(breakAfterAcquireFailure);
	dataSource.setDupCloseLogEnable(dupCloseLogEnable);
	dataSource.setEnable(enable);
	dataSource.setLogAbandoned(logAbandoned);
	dataSource.setLogDifferentThread(logDifferentThread);
	dataSource.setLoginTimeout(loginTimeout);
	dataSource.setAccessToUnderlyingConnectionAllowed(accessToUnderlyingConnectionAllowed);
	dataSource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
	dataSource.setQueryTimeout(queryTimeout);
	dataSource.setFailFast(failFast);
	dataSource.setMaxCreateTaskCount(maxCreateTaskCount);
	dataSource.setRemoveAbandoned(removeAbandoned);
	dataSource.setRemoveAbandonedTimeoutMillis(removeAbandonedTimeoutMillis);
	dataSource.setDefaultTransactionIsolation(defaultTransactionIsolation);
	dataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
	dataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
	dataSource.setMaxEvictableIdleTimeMillis(maxEvictableIdleTimeMillis);
	dataSource.setMaxOpenPreparedStatements(maxOpenPreparedStatements);
	dataSource.setNotFullTimeoutRetryCount(notFullTimeoutRetryCount);
	dataSource.setTimeBetweenLogStatsMillis(timeBetweenLogStatsMillis);
	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: 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: DataSourceUrlTest.java    From sofa-tracer with Apache License 2.0 4 votes vote down vote up
@Test
public void testGetDataSourceUrl() throws Throwable {
    // Druid
    DruidDataSource druidDataSource = new DruidDataSource();
    druidDataSource.setUrl("test-url");
    Method method = ReflectionUtils.findMethod(druidDataSource.getClass(),
        DataSourceUtils.METHOD_GET_URL);
    Assert.assertNotNull(method);
    Assert.assertEquals("test-url", method.invoke(druidDataSource));

    // dbcp
    BasicDataSource basicDataSource = new BasicDataSource();
    basicDataSource.setUrl("test-url");
    method = ReflectionUtils.findMethod(basicDataSource.getClass(),
        DataSourceUtils.METHOD_GET_URL);
    Assert.assertNotNull(method);
    Assert.assertEquals("test-url", method.invoke(basicDataSource));

    // tomcat datasource
    DataSource dataSource = new DataSource();
    dataSource.setUrl("test-url");
    method = ReflectionUtils.findMethod(dataSource.getClass(), DataSourceUtils.METHOD_GET_URL);
    Assert.assertNotNull(method);
    Assert.assertEquals("test-url", method.invoke(dataSource));

    // c3p0
    ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
    comboPooledDataSource.setJdbcUrl("test-url");
    method = ReflectionUtils.findMethod(comboPooledDataSource.getClass(),
        DataSourceUtils.METHOD_GET_JDBC_URL);
    Assert.assertNotNull(method);
    Assert.assertEquals("test-url", method.invoke(comboPooledDataSource));

    // hikari
    HikariDataSource hikariDataSource = new HikariDataSource();
    hikariDataSource.setJdbcUrl("test-url");
    method = ReflectionUtils.findMethod(hikariDataSource.getClass(),
        DataSourceUtils.METHOD_GET_JDBC_URL);
    Assert.assertNotNull(method);
    Assert.assertEquals("test-url", method.invoke(hikariDataSource));
}