com.alibaba.druid.pool.DruidDataSource Java Examples

The following examples show how to use com.alibaba.druid.pool.DruidDataSource. 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: 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 #2
Source File: DruidDataSourceConfig.java    From code with 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 #3
Source File: DynamicDBUtil.java    From jeecg-cloud with 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 #4
Source File: ExampleModule.java    From hasor with 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 #5
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 #6
Source File: DocOperateImpl.java    From singleton with 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 #7
Source File: MybatisConfig.java    From java_server with 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 #8
Source File: JdbcCoordinatorRepository.java    From myth with Apache License 2.0 6 votes vote down vote up
@Override
public void init(final String modelName, final MythConfig mythConfig) {
    dataSource = new DruidDataSource();
    final MythDbConfig tccDbConfig = mythConfig.getMythDbConfig();
    dataSource.setUrl(tccDbConfig.getUrl());
    dataSource.setDriverClassName(tccDbConfig.getDriverClassName());
    dataSource.setUsername(tccDbConfig.getUsername());
    dataSource.setPassword(tccDbConfig.getPassword());
    dataSource.setInitialSize(tccDbConfig.getInitialSize());
    dataSource.setMaxActive(tccDbConfig.getMaxActive());
    dataSource.setMinIdle(tccDbConfig.getMinIdle());
    dataSource.setMaxWait(tccDbConfig.getMaxWait());
    dataSource.setValidationQuery(tccDbConfig.getValidationQuery());
    dataSource.setTestOnBorrow(tccDbConfig.getTestOnBorrow());
    dataSource.setTestOnReturn(tccDbConfig.getTestOnReturn());
    dataSource.setTestWhileIdle(tccDbConfig.getTestWhileIdle());
    dataSource.setPoolPreparedStatements(tccDbConfig.getPoolPreparedStatements());
    dataSource.setMaxPoolPreparedStatementPerConnectionSize(tccDbConfig.getMaxPoolPreparedStatementPerConnectionSize());
    this.tableName = RepositoryPathUtils.buildDbTableName(modelName);
    executeUpdate(SqlHelper.buildCreateTableSql(tccDbConfig.getDriverClassName(), tableName));
}
 
Example #9
Source File: StrOperateImpl.java    From singleton with 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 #10
Source File: DruidDataSourceConfiguration.java    From druid-spring-boot with Apache License 2.0 6 votes vote down vote up
@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 #11
Source File: ESConfigMonitor.java    From canal-1.1.3 with 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 #12
Source File: DocOperateImpl.java    From singleton with 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 File: Message01ServiceImplTest.java    From pmq with 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 #14
Source File: JDBCTests.java    From elasticsearch-sql with 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 #15
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 #16
Source File: MyBatchConfig.java    From SpringBootBucket with MIT License 5 votes vote down vote up
/**
 * JobRepository,用来注册Job的容器
 * jobRepositor的定义需要dataSource和transactionManager,Spring Boot已为我们自动配置了
 * 这两个类,Spring可通过方法注入已有的Bean
 *
 * @param dataSource
 * @param transactionManager
 * @return
 * @throws Exception
 */
@Bean
public JobRepository jobRepository(DruidDataSource dataSource, PlatformTransactionManager transactionManager) throws Exception {
    JobRepositoryFactoryBean jobRepositoryFactoryBean = new JobRepositoryFactoryBean();
    jobRepositoryFactoryBean.setDataSource(dataSource);
    jobRepositoryFactoryBean.setTransactionManager(transactionManager);
    jobRepositoryFactoryBean.setDatabaseType(String.valueOf(DatabaseType.ORACLE));
    jobRepositoryFactoryBean.setMaxVarCharLength(5000);
    // 下面事务隔离级别的配置是针对Oracle的
    jobRepositoryFactoryBean.setIsolationLevelForCreate("ISOLATION_READ_COMMITTED");
    jobRepositoryFactoryBean.afterPropertiesSet();
    return jobRepositoryFactoryBean.getObject();
}
 
Example #17
Source File: DataDruidFactory.java    From DataSphereStudio with Apache License 2.0 5 votes vote down vote up
public static DruidDataSource getJobInstance(Properties props, Logger log) {
	if (jobInstance == null ) {
		synchronized (DataDruidFactory.class) {
			if(jobInstance == null) {
				try {
					jobInstance = createDataSource(props, log, "Job");
			    } catch (Exception e) {
			    	throw new RuntimeException("Error creating Druid DataSource", e);
			    }
			}
		}
	}
	return jobInstance;
}
 
Example #18
Source File: CommonUtil.java    From javabase with 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 #19
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 #20
Source File: MetaDataSourceConfig.java    From EasyReport with Apache License 2.0 5 votes vote down vote up
@Bean(name = "metaDataSource")
public DataSource dataSource() {
    DruidDataSource dds = secondDataSourceProperties().initializeDataSourceBuilder().type(DruidDataSource.class)
        .build();
    dds.setValidationQuery("select 1");
    return dds;
}
 
Example #21
Source File: DruidConfig.java    From ruoyiplus with 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 #22
Source File: DruidMetricsGaugeSetTest.java    From metrics with Apache License 2.0 5 votes vote down vote up
@Test
public void testDruidMetricsSet() throws Exception {
    DruidDataSource dataSource = new DruidDataSource();
    dataSource.setUrl("jdbc:mock:xx");
    dataSource.setFilters("mergeStat");
    dataSource.setDbType("mysql");

    ManualClock clock = new ManualClock();
    MetricName name = new MetricName("druid2.sql");
    MetricManager.register("druid2", name,
            new DruidMetricsGaugeSet(5, TimeUnit.SECONDS, clock,20, name));

    doSelect(dataSource, 1000, 2000);
    doUpdate(dataSource, 2000, 2500);
    clock.addSeconds(6);

    SortedMap<MetricName, Gauge> druidMetrics = MetricManager.getIMetricManager().getGauges("druid2", MetricFilter.ALL);
    Assert.assertEquals(26, druidMetrics.size());
    Gauge g = druidMetrics.get(new MetricName("druid2.sql.ExecuteCount")
            .tagged("sql", "SELECT *\nFROM t\nWHERE t.id = ?"));
    Assert.assertEquals(1000L, g.getValue());

    doSelect(dataSource, 2000, 2500);
    clock.addSeconds(6);

    druidMetrics = MetricManager.getIMetricManager().getGauges("druid2", MetricFilter.ALL);
    Assert.assertEquals(26, druidMetrics.size());
    Gauge g2 = druidMetrics.get(new MetricName("druid2.sql.ExecuteCount")
            .tagged("sql", "SELECT *\nFROM t\nWHERE t.id = ?"));
    Assert.assertEquals(500L, g2.getValue());
}
 
Example #23
Source File: MasterDruidDataSourceConfig.java    From SpringBoot-Study with Apache License 2.0 5 votes vote down vote up
@ConfigurationProperties(prefix = "spring.datasource.master")
@Bean(name = "masterDataSource")
@Primary
public DataSource masterDataSource() {
    DruidDataSource dataSource = new DruidDataSource();
    try {
        dataSource.setFilters("stat,wall,log4j");
    } catch (SQLException e) {
        //
    }
    return dataSource;
}
 
Example #24
Source File: StrOperateImpl.java    From singleton with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public int delStrBykey(String productName, String version, String component, String locale, String key,
		JdbcTemplate jdbcTemplate) {
	// TODO Auto-generated method stub
	
	logger.debug(((DruidDataSource)(jdbcTemplate.getDataSource())).getName());
	
	String sql=  String.format("update vip_msg  set messages = messages #- '{%s}'::text[] where product = ? and version = ? and component= ? and locale = ?",key);   
	logger.debug(sql);
	logger.debug(String.join(", ", productName, version, component, locale));
	 return  jdbcTemplate.update(sql, productName, version, component,locale);
	
}
 
Example #25
Source File: DBTable2JavaBean.java    From framework with Apache License 2.0 5 votes vote down vote up
/**
 * Description: <br>
 * 
 * @author yang.zhipeng <br>
 * @taskId <br>
 * @throws Exception <br>
 */
public void export() throws Exception {

    saveConfig();
    String tablename = textFields[0].getText();
    String packname = textFields[1].getText();
    String dirstr = textFields[2].getText(); // 空表示当前目录

    if (dataSource == null) {
        DruidDataSource dbs = new DruidDataSource();
        dbs.setUrl(textFields[NUM_3].getText());
        dbs.setUsername(textFields[NUM_4].getText());
        dbs.setPassword(textFields[NUM_5].getText());
        dbs.setValidationQuery("select 1");
        dbs.init();
        dataSource = dbs;
    }

    if (StringUtils.isEmpty(dirstr)) {
        tips[2].setText("给你导到根目录去了");
        dirstr = GlobalConstants.BLANK;
    }
    else {
        tips[2].setText(GlobalConstants.BLANK);
    }

    if (StringUtils.isEmpty(packname)) {
        tips[1].setText("w靠,你居然不写包名");
        packname = GlobalConstants.BLANK;
    }
    else {
        tips[1].setText(GlobalConstants.BLANK);
    }

    export(dirstr, packname, tablename);

}
 
Example #26
Source File: DbNodeServiceImplTest.java    From pmq with Apache License 2.0 5 votes vote down vote up
@Test
public void createDataSourceTest() throws SQLException {
	DruidDataSource dataSource = mock(DruidDataSource.class);
	DbNodeServiceImpl.DataSourceFactory dataSourceFactory = new DbNodeServiceImpl.DataSourceFactory() {
		@Override
		public DruidDataSource createDataSource() {
			// TODO Auto-generated method stub
			return dataSource;
		}
	};
	dbNodeServiceImpl.setDataSourceFactory(dataSourceFactory);
	DbNodeEntity dbNodeEntity = new DbNodeEntity();

	dbNodeEntity.setIp("fasaf");
	dbNodeEntity.setDbUserName("faf");
	dbNodeEntity.setDbPass("aff");
	dbNodeEntity.setPort(2342);

	dbNodeEntity.setIpBak("faf");
	dbNodeEntity.setDbUserNameBak("fa");
	dbNodeEntity.setDbPassBak("faf");
	dbNodeEntity.setPortBak(3);

	dbNodeServiceImpl.createDataSource(dbNodeEntity);
	dbNodeServiceImpl.createDataSource(dbNodeEntity);
	assertEquals(true, dbNodeServiceImpl.cacheDataMap.get().size() == 2);

	doThrow(new SQLException()).when(dataSource).init();
	dbNodeServiceImpl.dbCreated.clear();
	dbNodeServiceImpl.cacheDataMap.set(new HashMap<String, DataSource>());
	dbNodeServiceImpl.createDataSource(dbNodeEntity);

	assertEquals(true, dbNodeServiceImpl.cacheDataMap.get().size() == 0);
}
 
Example #27
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 #28
Source File: DruidDataSourceFactory.java    From tsharding with MIT License 5 votes vote down vote up
@Override
public DruidDataSource getDataSource(DataSourceConfig config) throws SQLException {
    DruidDataSource dataSource = new DruidDataSource();
    dataSource.setUrl(config.getUrl());
    dataSource.setUsername(config.getUsername());
    dataSource.setPassword(config.getPassword());
    // pool config
    dataSource.setInitialSize(config.getInitialPoolSize());
    dataSource.setMinIdle(config.getMinPoolSize());
    dataSource.setMaxActive(config.getMaxPoolSize());

    // common config
    dataSource.setFilters("stat");
    dataSource.setMaxWait(1000);
    dataSource.setValidationQuery("SELECT 'x'");
    dataSource.setTestWhileIdle(true);
    dataSource.setTestOnBorrow(false);
    dataSource.setTestOnReturn(false);
    dataSource.setTimeBetweenEvictionRunsMillis(60000);
    dataSource.setMinEvictableIdleTimeMillis(120000);
    dataSource.setTimeBetweenLogStatsMillis(0);

    dataSource.setProxyFilters(filters);

    dataSource.init();
    return dataSource;
}
 
Example #29
Source File: DbNodeServiceImpl.java    From pmq with Apache License 2.0 5 votes vote down vote up
public void initDataSource(DbNodeEntity t1, String key, Map<String, DataSource> dataMap, boolean isMaster,
		Transaction transaction) {
	try {
		// if (soaConfig.isUseDruid())
		{
			DruidDataSource dataSource = dataSourceFactory.createDataSource();
			dataSource.setDriverClassName("com.mysql.jdbc.Driver");
			if (isMaster) {
				dataSource.setUsername(t1.getDbUserName());
				dataSource.setPassword(t1.getDbPass());
			} else {
				dataSource.setUsername(t1.getDbUserNameBak());
				dataSource.setPassword(t1.getDbPassBak());
			}
			// dataSource.setUrl(t1.getConStr());
			dataSource.setUrl(getCon(t1, isMaster));
			dataSource.setInitialSize(soaConfig.getInitDbCount());
			dataSource.setMinIdle(soaConfig.getInitDbCount());
			dataSource.setMaxActive(soaConfig.getMaxDbCount());
			dataSource.setConnectionInitSqls(Arrays.asList("set names utf8mb4;"));
			dataSource.init();
			dbCreated.put(key, true);
			log.info(dataSource.getUrl() + "数据源创建成功!dataSource_created");
			dataMap.put(key, dataSource);
			transaction.setStatus(Transaction.SUCCESS);
		}
	} catch (Exception e) {
		transaction.setStatus(e);
		log.error("initDataSource_error", e);
	}
}
 
Example #30
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;
}