相比基础版本,我们用的是阿里巴巴的com.alibaba.druid.pool.DruidDataSource
直接上代码:
- 一个数据源的DTO,这个还是沿用基础版本的数据源DTO对象
package ...;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
@Data
@ApiModel(value = "数据源对象")
public class CfgDataSource {
@ApiModelProperty(value = "数据源ID,序列主键")
private int datasourceId;
@ApiModelProperty(value = "数据库URL")
private String dbUrl;
@ApiModelProperty(value = "数据库用户名")
private String dbUserName;
@ApiModelProperty(value = "数据库密码")
private String dbPassword;
@ApiModelProperty(value = "最大连接数,默认值:10")
private int maxActive;
@ApiModelProperty(value = "最大等待时间(秒),默认值:600")
private int connectionTimeOut;
@ApiModelProperty(value = "数据源名称")
private String dbSourceName;
@ApiModelProperty(value = "最大空闲连接数")
private int maxIdle;
@ApiModelProperty(value = "超时时间")
private int removeAbandoneTimeout;
@ApiModelProperty(value = "数据库类型,oracle、mysql")
private String dbType;
@ApiModelProperty(value = "数据库驱动")
private String dbDriverClassName;
}
- 获取数据源
package ...;
import com.alibaba.druid.pool.DruidDataSource;
import ...CfgDataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@Slf4j
@Component
public class DynamicDataSourceManager {
/**
* druid连接池Map
*/
private static final Map<Long, DruidDataSource> DRUID_DATA_SOURCE_POOL = new ConcurrentHashMap<>();
/**
* 获取数据源JdbcTemplate
*
* @param datasource 数据源
* @return JdbcTemplate
*/
public JdbcTemplate getDataSourcePool(CfgDataSource datasource) {
Long newDatasourceId = datasource.getDatasourceId();
DruidDataSource druidDataSource = DRUID_DATA_SOURCE_POOL.get(newDatasourceId);
if (null != druidDataSource) {
return new JdbcTemplate(druidDataSource);
} else {
if (!DRUID_DATA_SOURCE_POOL.isEmpty()){
Long oldDatasourceId = new ArrayList<>(DRUID_DATA_SOURCE_POOL.keySet()).get(0);
DruidDataSource oldDruidDataSource = DRUID_DATA_SOURCE_POOL.get(oldDatasourceId);
oldDruidDataSource.close();
DRUID_DATA_SOURCE_POOL.clear();
}
druidDataSource = new DruidDataSource();
druidDataSource.setDriverClassName(datasource.getDbDriverClassName());
druidDataSource.setUrl(datasource.getDbUrl());
druidDataSource.setUsername(datasource.getDbUsername());
druidDataSource.setPassword(datasource.getDbPassword());
druidDataSource.setBreakAfterAcquireFailure(true);
// 防止密码错误无限重连
druidDataSource.setConnectionErrorRetryAttempts(0);
druidDataSource.setTimeBetweenConnectErrorMillis(1);
try {
druidDataSource.init();
DRUID_DATA_SOURCE_POOL.put(newDatasourceId, druidDataSource);
} catch (SQLException e) {
druidDataSource.close();
}
return new JdbcTemplate(druidDataSource);
}
}
}
使用方法与基础版本使用相同,本文只是对连接池进行了优化,使用druid连接池,并新增了连接池关闭方法,避免OOM。