Java Code Examples for com.alibaba.druid.pool.DruidDataSource

The following examples show how to use com.alibaba.druid.pool.DruidDataSource. These examples are extracted from open source projects. 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 Project: jeecg-cloud   Source File: DynamicDBUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 通过 dbKey ,获取数据源
 *
 * @param dbKey
 * @return
 */
public static DruidDataSource getDbSourceByDbKey(final String dbKey) {
    //获取多数据源配置
    DynamicDataSourceModel dbSource = DataSourceCachePool.getCacheDynamicDataSourceModel(dbKey);
    //先判断缓存中是否存在数据库链接
    DruidDataSource cacheDbSource = DataSourceCachePool.getCacheBasicDataSource(dbKey);
    if (cacheDbSource != null && !cacheDbSource.isClosed()) {
        log.debug("--------getDbSourceBydbKey------------------从缓存中获取DB连接-------------------");
        return cacheDbSource;
    } else {
        DruidDataSource dataSource = getJdbcDataSource(dbSource);
        if(dataSource!=null && dataSource.isEnable()){
            DataSourceCachePool.putCacheBasicDataSource(dbKey, dataSource);
        }else{
            throw new JeecgBootException("动态数据源连接失败,dbKey:"+dbKey);
        }
        log.info("--------getDbSourceBydbKey------------------创建DB数据库连接-------------------");
        return dataSource;
    }
}
 
Example 2
Source Project: hasor   Source File: ExampleModule.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void loadModule(ApiBinder apiBinder) throws Throwable {
    // .数据库
    DruidDataSource dataSource = new DruidDataSource();
    dataSource.setDriverClassName("com.mysql.jdbc.Driver");
    dataSource.setUrl(this.dataSourceUrl);
    dataSource.setUsername(this.username);
    dataSource.setPassword(this.password);
    dataSource.setInitialSize(1);
    dataSource.setMinIdle(1);
    dataSource.setMaxActive(5);
    apiBinder.installModule(new JdbcModule(Level.Full, dataSource));
    // .DataQL
    //        apiBinder.tryCast(QueryApiBinder.class).loadFragment(apiBinder.findClass(DimFragment.class));
    //        apiBinder.tryCast(QueryApiBinder.class).loadUdfSource(apiBinder.findClass(DimUdfSource.class));
    //
    ConsoleApiBinder.HostBuilder hostBuilder = apiBinder.tryCast(ConsoleApiBinder.class).asHostWithSTDO().answerExit();
    hostBuilder.preCommand(this.applicationArguments.getSourceArgs()).loadExecutor(apiBinder.findClass(Tel.class));
}
 
Example 3
Source Project: singleton   Source File: DocOperateImpl.java    License: Eclipse Public License 2.0 6 votes vote down vote up
private  int updateCompDoc(String productName, String version, String component, String locale,
		Map<String, String> messages, JdbcTemplate jdbcTemplate) { // TODO Auto-generated method stub
	String updateSql = "update vip_msg  set messages = ? ::jsonb  where product = ? and version = ? and component= ? and locale = ?";
	logger.debug(((DruidDataSource) (jdbcTemplate.getDataSource())).getName());
	logger.debug(updateSql);
	logger.debug(String.join(", ", productName, version, component, locale));
	
	String msg = null;
	try {
		ObjectMapper objectMapper = new ObjectMapper();
		msg = objectMapper.writeValueAsString(messages);
	} catch (JsonProcessingException e) { // TODO Auto-generated catch block e.printStackTrace();
		logger.warn(e.getMessage(), e);
		return 0;
	}
	logger.debug ("update json---"+msg);
	return jdbcTemplate.update(updateSql, msg, productName, version, component, locale);
}
 
Example 4
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    if (bean instanceof DruidDataSource) {
        // 设置 Druid 名称
        ((DruidDataSource) bean).setName(beanName);
        // 将 'spring.datasource.druid.data-sources.${name}' 的配置绑定到 Bean
        if (!resolver.getSubProperties(EMPTY).isEmpty()) {
            PropertySourcesBinder binder = new PropertySourcesBinder(environment);
            binder.bindTo(PREFIX + beanName, bean);
        }
        // 用户自定义配置
        if (customizers != null && !customizers.isEmpty()) {
            for (DruidDataSourceCustomizer customizer : customizers) {
                customizer.customize((DruidDataSource) bean);
            }
        }
        boolean isSingle = BEAN_NAME.equals(beanName);
        if (isSingle) {
            log.debug("druid data-source init...");
        } else {
            log.debug("druid {}-data-source init...", beanName);
        }
    }
    return bean;
}
 
Example 5
Source Project: canal-1.1.3   Source File: ESConfigMonitor.java    License: Apache License 2.0 6 votes vote down vote up
private void addConfigToCache(File file, ESSyncConfig config) {
    esAdapter.getEsSyncConfig().put(file.getName(), config);

    SchemaItem schemaItem = SqlParser.parse(config.getEsMapping().getSql());
    config.getEsMapping().setSchemaItem(schemaItem);

    DruidDataSource dataSource = DatasourceConfig.DATA_SOURCES.get(config.getDataSourceKey());
    if (dataSource == null || dataSource.getUrl() == null) {
        throw new RuntimeException("No data source found: " + config.getDataSourceKey());
    }
    Pattern pattern = Pattern.compile(".*:(.*)://.*/(.*)\\?.*$");
    Matcher matcher = pattern.matcher(dataSource.getUrl());
    if (!matcher.find()) {
        throw new RuntimeException("Not found the schema of jdbc-url: " + config.getDataSourceKey());
    }
    String schema = matcher.group(2);

    schemaItem.getAliasTableItems().values().forEach(tableItem -> {
        Map<String, ESSyncConfig> esSyncConfigMap = esAdapter.getDbTableEsSyncConfig()
            .computeIfAbsent(schema + "-" + tableItem.getTableName(), k -> new HashMap<>());
        esSyncConfigMap.put(file.getName(), config);
    });

}
 
Example 6
Source Project: pmq   Source File: Message01ServiceImplTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void getMaxId1Test() {
	assertEquals(true, message01ServiceImpl.getMaxId().size() == 0);
	message01ServiceImpl.setDbId(1);
	List<TableInfoEntity> dataLst = new ArrayList<TableInfoEntity>();
	TableInfoEntity tableInfoEntity = new TableInfoEntity();
	tableInfoEntity.setAutoIncrement(1L);
	tableInfoEntity.setTableSchema("test");
	tableInfoEntity.setTbName("t1");

	dataLst.add(tableInfoEntity);
	tableInfoEntity = new TableInfoEntity();
	tableInfoEntity.setAutoIncrement(1L);
	tableInfoEntity.setTableSchema("test");
	tableInfoEntity.setTbName("t2");
	dataLst.add(tableInfoEntity);
	when(message01Repository.getMaxIdByDb()).thenReturn(dataLst);
	when(dbNodeService.getDataSource(anyLong(), anyBoolean())).thenReturn(new DruidDataSource());
	assertEquals(true, message01ServiceImpl.getMaxId().size() == 1);

	message01ServiceImpl.setDbId(1);
	doThrow(new RuntimeException()).when(message01Repository).getMaxIdByDb();
	assertEquals(true, message01ServiceImpl.getMaxId().size() == 0);
}
 
Example 7
Source Project: myth   Source File: JdbcCoordinatorRepository.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void init(final String modelName, final MythConfig mythConfig) {
    dataSource = new DruidDataSource();
    final MythDbConfig tccDbConfig = mythConfig.getMythDbConfig();
    dataSource.setUrl(tccDbConfig.getUrl());
    dataSource.setDriverClassName(tccDbConfig.getDriverClassName());
    dataSource.setUsername(tccDbConfig.getUsername());
    dataSource.setPassword(tccDbConfig.getPassword());
    dataSource.setInitialSize(tccDbConfig.getInitialSize());
    dataSource.setMaxActive(tccDbConfig.getMaxActive());
    dataSource.setMinIdle(tccDbConfig.getMinIdle());
    dataSource.setMaxWait(tccDbConfig.getMaxWait());
    dataSource.setValidationQuery(tccDbConfig.getValidationQuery());
    dataSource.setTestOnBorrow(tccDbConfig.getTestOnBorrow());
    dataSource.setTestOnReturn(tccDbConfig.getTestOnReturn());
    dataSource.setTestWhileIdle(tccDbConfig.getTestWhileIdle());
    dataSource.setPoolPreparedStatements(tccDbConfig.getPoolPreparedStatements());
    dataSource.setMaxPoolPreparedStatementPerConnectionSize(tccDbConfig.getMaxPoolPreparedStatementPerConnectionSize());
    this.tableName = RepositoryPathUtils.buildDbTableName(modelName);
    executeUpdate(SqlHelper.buildCreateTableSql(tccDbConfig.getDriverClassName(), tableName));
}
 
Example 8
Source Project: java_server   Source File: MybatisConfig.java    License: MIT License 6 votes vote down vote up
private void druidSettings(DruidDataSource druidDataSource) throws Exception {
    druidDataSource.setMaxActive(1000);
    druidDataSource.setInitialSize(0);
    druidDataSource.setMinIdle(0);
    druidDataSource.setMaxWait(60000);
    druidDataSource.setPoolPreparedStatements(true);
    druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(100);
    druidDataSource.setTestOnBorrow(false);
    druidDataSource.setTestOnReturn(false);
    druidDataSource.setTestWhileIdle(true);
    druidDataSource.setTimeBetweenEvictionRunsMillis(6000);
    druidDataSource.setMinEvictableIdleTimeMillis(2520000);
    druidDataSource.setRemoveAbandoned(true);
    druidDataSource.setRemoveAbandonedTimeout(18000);
    druidDataSource.setLogAbandoned(true);
    druidDataSource.setFilters("mergeStat");
    druidDataSource.setDriver(new Driver());
}
 
Example 9
@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 10
Source Project: saluki   Source File: SingleDataSourceConfig.java    License: 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 11
Source Project: code   Source File: DruidDataSourceConfig.java    License: Apache License 2.0 6 votes vote down vote up
@Bean
public DataSource dataSource() throws SQLException {
	DruidDataSource ds = new DruidDataSource();
	ds.setDriverClassName(druidSettings.getDriverClassName());
	DRIVER_CLASSNAME = druidSettings.getDriverClassName();
	ds.setUrl(druidSettings.getUrl());
	ds.setUsername(druidSettings.getUsername());
	ds.setPassword(druidSettings.getPassword());
	ds.setInitialSize(druidSettings.getInitialSize());
	ds.setMinIdle(druidSettings.getMinIdle());
	ds.setMaxActive(druidSettings.getMaxActive());
	ds.setTimeBetweenEvictionRunsMillis(druidSettings.getTimeBetweenEvictionRunsMillis());
	ds.setMinEvictableIdleTimeMillis(druidSettings.getMinEvictableIdleTimeMillis());
	ds.setValidationQuery(druidSettings.getValidationQuery());
	ds.setTestWhileIdle(druidSettings.isTestWhileIdle());
	ds.setTestOnBorrow(druidSettings.isTestOnBorrow());
	ds.setTestOnReturn(druidSettings.isTestOnReturn());
	ds.setPoolPreparedStatements(druidSettings.isPoolPreparedStatements());
	ds.setMaxPoolPreparedStatementPerConnectionSize(druidSettings.getMaxPoolPreparedStatementPerConnectionSize());
	ds.setFilters(druidSettings.getFilters());
	ds.setConnectionProperties(druidSettings.getConnectionProperties());
	logger.info(" druid datasource config : {} ", ds);
	return ds;
}
 
Example 12
Source Project: singleton   Source File: DocOperateImpl.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Override
public int saveDoc(I18nDocument content, JdbcTemplate jdbcTemplate) {
	// TODO Auto-generated method stub
	String tableName = "vip_msg_"+content.getProduct().toLowerCase();
	String saveSql = "insert into "+tableName+" (product, version, component, locale, messages, crt_time) values (? ,? ,? ,? ,?::jsonb, CURRENT_TIMESTAMP)";
	logger.debug(((DruidDataSource) (jdbcTemplate.getDataSource())).getName());
	logger.debug(saveSql);
	logger.debug(String.join(", ", content.getProduct(), content.getVersion(), content.getComponent(),
			content.getLocale()));
	String msg = null;
	try {
		ObjectMapper objectMapper = new ObjectMapper();
		msg = objectMapper.writeValueAsString(content.getMessages());
	} catch (JsonProcessingException e) {
		// TODO Auto-generated catch block
		
		logger.error(e.getMessage(), e);
	}
	return jdbcTemplate.update(saveSql, content.getProduct(), content.getVersion(), content.getComponent(),
			content.getLocale(), msg);

}
 
Example 13
Source Project: elasticsearch-sql   Source File: JDBCTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testJDBCWithParameter() throws Exception {
    Properties properties = new Properties();
    properties.put(PROP_URL, "jdbc:elasticsearch://127.0.0.1:9300/" + TestsConstants.TEST_INDEX_ACCOUNT);
    properties.put(PROP_CONNECTIONPROPERTIES, "client.transport.ignore_cluster_name=true");
    try (DruidDataSource dds = (DruidDataSource) ElasticSearchDruidDataSourceFactory.createDataSource(properties);
         Connection connection = dds.getConnection();
         PreparedStatement ps = connection.prepareStatement("SELECT gender,lastname,age from " + TestsConstants.TEST_INDEX_ACCOUNT + " where lastname=?")) {
        // set parameter
        ps.setString(1, "Heath");
        ResultSet resultSet = ps.executeQuery();

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

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

        Assert.assertEquals(1, result.size());
        Assert.assertEquals("Heath,39,F", result.get(0));
    }
}
 
Example 14
Source Project: singleton   Source File: StrOperateImpl.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Override
public int addStrs(I18nString n18Str, JdbcTemplate jdbcTemplate) {
	// TODO Auto-generated method stub
	String sqlhead =  "update vip_msg set messages = ";   
	String sqltail= " where product = ? and version = ? and component= ? and locale = ?"; 
	int i=0;
	String updateStr =null;
	for(Entry<String, String> entry: n18Str.getMessages().entrySet()) {
		if(i<1) { 
			updateStr = "jsonb_set(messages, '{"+entry.getKey()+"}', '\""+entry.getValue()+"\"'::jsonb,true)";
		}else {
			updateStr = "jsonb_set("+updateStr+", '{"+entry.getKey()+"}', '\""+entry.getValue()+"\"'::jsonb,true)";
		}
		
		i++;
		
	}


	String sql = sqlhead + updateStr + sqltail;
	logger.debug(((DruidDataSource)(jdbcTemplate.getDataSource())).getName());
	logger.debug(sql);
	int result = jdbcTemplate.update(sql, n18Str.getProduct(), n18Str.getVersion(), n18Str.getComponent(),n18Str.getLocale());
	return result;
}
 
Example 15
Source Project: singleton   Source File: DocOperateImpl.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Override
public List<String> getLocaleList(String productName, String version, JdbcTemplate jdbcTemplate) {

	String localeSql = "select v.locale from vip_msg v where v.product = ? and v.version = ? group by v.locale";
	String[] params = { productName, version };

	logger.debug(((DruidDataSource) (jdbcTemplate.getDataSource())).getName());
	logger.debug(localeSql);
	logger.debug(String.join(", ", params));
	List<String> result = jdbcTemplate.queryForList(localeSql, params, String.class);

	return result;
}
 
Example 16
Source Project: SpringBoot-Study   Source File: DruidDataSourceConfig.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * DataSource 配置
 * @return
 */
@ConfigurationProperties(prefix = "spring.datasource.druid.write")
@Bean(name = "writeDruidDataSource")
@Primary
public DataSource writeDruidDataSource() {
    return new DruidDataSource();
}
 
Example 17
Source Project: canal   Source File: AdapterCanalConfig.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("resource")
public void setSrcDataSources(Map<String, DatasourceConfig> srcDataSources) {
    this.srcDataSources = srcDataSources;

    if (srcDataSources != null) {
        for (Map.Entry<String, DatasourceConfig> entry : srcDataSources.entrySet()) {
            DatasourceConfig datasourceConfig = entry.getValue();
            // 加载数据源连接池
            DruidDataSource ds = new DruidDataSource();
            ds.setDriverClassName(datasourceConfig.getDriver());
            ds.setUrl(datasourceConfig.getUrl());
            ds.setUsername(datasourceConfig.getUsername());
            ds.setPassword(datasourceConfig.getPassword());
            ds.setInitialSize(1);
            ds.setMinIdle(1);
            ds.setMaxActive(datasourceConfig.getMaxActive());
            ds.setMaxWait(60000);
            ds.setTimeBetweenEvictionRunsMillis(60000);
            ds.setMinEvictableIdleTimeMillis(300000);
            ds.setValidationQuery("select 1");
            try {
                ds.init();
            } catch (SQLException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
            DatasourceConfig.DATA_SOURCES.put(entry.getKey(), ds);
        }
    }
}
 
Example 18
Source Project: supplierShop   Source File: DruidConfig.java    License: MIT License 5 votes vote down vote up
@Bean
@ConfigurationProperties("spring.datasource.druid.slave")
@ConditionalOnProperty(prefix = "spring.datasource.druid.slave", name = "enabled", havingValue = "true")
public DataSource slaveDataSource(DruidProperties druidProperties)
{
    DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
    return druidProperties.dataSource(dataSource);
}
 
Example 19
Source Project: sdmq   Source File: DruidConfig.java    License: 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 20
Source Project: DataSphereStudio   Source File: EventDruidFactory.java    License: Apache License 2.0 5 votes vote down vote up
public static DruidDataSource getMsgInstance(Properties props, Logger log) {
	if (msgInstance == null ) {
		synchronized (EventDruidFactory.class) {
			if(msgInstance == null) {
				try {
					msgInstance = createDataSource(props, log, "Msg");
			    } catch (Exception e) {
			    	throw new RuntimeException("Error creating Druid DataSource", e);
			    }
			}
		}
	}
	return msgInstance;
}
 
Example 21
Source Project: Mars-Java   Source File: InitJdbc.java    License: MIT License 5 votes vote down vote up
/**
 * 加载数据源
 * @throws Exception
 */
private void loadDataSource() throws Exception {
	Map<String,DruidDataSource> druidDataSourceMap = DBHelper.getDruidDataSources();
	marsSpace.setAttr(MarsConstant.DATA_SOURCE_MAP,druidDataSourceMap);

	/* 保存默认数据源名称 */
	marsSpace.setAttr(MarsConstant.DEFAULT_DATASOURCE_NAME, DBHelper.getDefaultDataSourceName());
}
 
Example 22
Source Project: spring-boot-shiro   Source File: DruidDataSourceConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
@Primary  //在同样的DataSource中,首先使用被标注的DataSource
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) {
        log.error("druid配置初始化失败", e);
    }
    datasource.setConnectionProperties(connectionProperties);

    return datasource;
}
 
Example 23
Source Project: honeycomb   Source File: BaseTests.java    License: MIT License 5 votes vote down vote up
@Test
public void testDruid() throws SQLException, InterruptedException{
    DruidDataSource dataSource = new DruidDataSource();
    dataSource.setUrl("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=false&transformedBitIsBoolean=true&zeroDateTimeBehavior=CONVERT_TO_NULL&serverTimezone=Asia/Shanghai");
    dataSource.setUsername("root");
    dataSource.setPassword("root");
    dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
    dataSource.setMaxActive(300);
    dataSource.setInitialSize(0);
    dataSource.setMaxWait(Long.MAX_VALUE);
    dataSource.setMinIdle(100);
    dataSource.setTimeBetweenEvictionRunsMillis(1000 * 5);

    test(dataSource, 1000 * 60);
}
 
Example 24
Source Project: jeecg-boot   Source File: DynamicDBUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 关闭数据库连接池
 *
 * @param dbKey
 * @return
 */
public static void closeDbKey(final String dbKey) {
    DruidDataSource dataSource = getDbSourceByDbKey(dbKey);
    try {
        if (dataSource != null && !dataSource.isClosed()) {
            dataSource.getConnection().commit();
            dataSource.getConnection().close();
            dataSource.close();
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
}
 
Example 25
Source Project: jeecg-cloud   Source File: DataSourceCachePool.java    License: Apache License 2.0 5 votes vote down vote up
public static void removeCache(String dbKey) {
    //关闭数据源连接
    DruidDataSource druidDataSource = dbSources.get(dbKey);
    if(druidDataSource!=null && druidDataSource.isEnable()){
        druidDataSource.close();
    }
    //清空redis缓存
    getRedisTemplate().delete(CacheConstant.SYS_DYNAMICDB_CACHE + dbKey);
    //清空缓存
    dbSources.remove(dbKey);
}
 
Example 26
Source Project: pmq   Source File: MySqlDatasourceConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
@Bean(name = "mysqlDataSource")
    @ConfigurationProperties(prefix = "spring.datasource")
    @Primary
    public DataSource mysqlDataSource() {
    	DruidDataSource druidDataSource= new DruidDataSource();
//    	druidDataSource.setUrl("jdbc:mysql://localhost:3408/mq_basic");
//    	druidDataSource.setUsername("root");
//    	druidDataSource.setPassword("root");
    	return druidDataSource;
    }
 
Example 27
Source Project: sdmq   Source File: RedisQueueAutoConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public RdbStore rdbStore() {
    try {
        DruidDataSource ds = (DruidDataSource) druidConfig.newInstanceDruidDataSource();
        return new RdbStore(ds);
    } catch (Exception e) {
        LOGGER.error(e.getMessage());
        throw new RuntimeException(e);
    }
}
 
Example 28
Source Project: SpringMVC-Project   Source File: SegmentService.java    License: MIT License 5 votes vote down vote up
public SegmentService() throws SQLException, InitException {
    Properties properties = PropertyFactory.getProperties();
    boolean flag = Boolean.parseBoolean(properties.getProperty(Constants.LEAF_SEGMENT_ENABLE, "true"));
    if (flag) {
        // Config dataSource
        dataSource = new DruidDataSource();
        dataSource.setUrl(properties.getProperty(Constants.LEAF_JDBC_URL));
        dataSource.setUsername(properties.getProperty(Constants.LEAF_JDBC_USERNAME));
        dataSource.setPassword(properties.getProperty(Constants.LEAF_JDBC_PASSWORD));
        dataSource.init();

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

        // Config ID Gen
        idGen = new SegmentIDGenImpl();
        ((SegmentIDGenImpl) idGen).setDao(dao);
        if (idGen.init()) {
            logger.info("Segment Service Init Successfully");
        } else {
            throw new InitException("Segment Service Init Fail");
        }
    } else {
        idGen = new ZeroIDGen();
        logger.info("Zero ID Gen Service Init Successfully");
    }
}
 
Example 29
Source Project: javabase   Source File: CommonUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static DataSource createDataSource(final String dataSourceName) {
	DruidDataSource dataSource = new DruidDataSource();
	dataSource.setDriverClassName("com.mysql.jdbc.Driver");
	dataSource.setUrl(String.format("jdbc:mysql://123.56.118.135:3306/%s", dataSourceName));
	dataSource.setUsername("mobile");
	dataSource.setPassword("mobile");
	return dataSource;
}
 
Example 30
Source Project: pmq   Source File: DbNodeServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
public void initDataSource(DbNodeEntity t1, String key, Map<String, DataSource> dataMap, boolean isMaster,
		Transaction transaction) {
	try {
		// if (soaConfig.isUseDruid())
		{
			DruidDataSource dataSource = dataSourceFactory.createDataSource();
			dataSource.setDriverClassName("com.mysql.jdbc.Driver");
			if (isMaster) {
				dataSource.setUsername(t1.getDbUserName());
				dataSource.setPassword(t1.getDbPass());
			} else {
				dataSource.setUsername(t1.getDbUserNameBak());
				dataSource.setPassword(t1.getDbPassBak());
			}
			// dataSource.setUrl(t1.getConStr());
			dataSource.setUrl(getCon(t1, isMaster));
			dataSource.setInitialSize(soaConfig.getInitDbCount());
			dataSource.setMinIdle(soaConfig.getInitDbCount());
			dataSource.setMaxActive(soaConfig.getMaxDbCount());
			dataSource.setConnectionInitSqls(Arrays.asList("set names utf8mb4;"));
			dataSource.init();
			dbCreated.put(key, true);
			log.info(dataSource.getUrl() + "数据源创建成功!dataSource_created");
			dataMap.put(key, dataSource);
			transaction.setStatus(Transaction.SUCCESS);
		}
	} catch (Exception e) {
		transaction.setStatus(e);
		log.error("initDataSource_error", e);
	}
}