This commit is contained in:
zhangchenbiao
2023-06-06 17:45:20 +08:00
parent 7370e327f0
commit bf965a2835
4 changed files with 0 additions and 267 deletions

View File

@@ -1,15 +1,8 @@
package com.cool.store.config;
import com.alibaba.fastjson.JSONObject;
import com.cool.store.config.datasource.DynamicDataSourceServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.List;
/**
* @author zhangchenbiao
* @FileName: CommonBeanConfig
@@ -20,20 +13,5 @@ import java.util.List;
@Component
public class CommonBeanConfig {
@Autowired
private DynamicDataSourceServiceImpl dynamicDataSourceServiceImpl;
@PostConstruct
public void loadDataSource(){
List<DatasourceInfoDTO> dbServerList = dynamicDataSourceServiceImpl.getDbNodes();
if (CollectionUtils.isEmpty(dbServerList)) {
return;
}
dbServerList.forEach(node -> {
dynamicDataSourceServiceImpl.createDataSource(node);
});
log.info("数据源加载完毕:{}", JSONObject.toJSONString(dbServerList));
}
}

View File

@@ -1,105 +0,0 @@
package com.cool.store.config.datasource;
import com.cool.store.constants.CommonConstants;
import com.cool.store.context.DataSourceContext;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.AbstractDataSource;
import org.springframework.stereotype.Component;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;
@Primary
@Component
public class DynamicDataSource extends AbstractDataSource {
private static final Logger logger = LoggerFactory.getLogger(DynamicDataSource.class);
@Autowired
private DataSource defaultDataSource;
@Autowired
private DynamicDataSourceServiceImpl dynamicDataSourceService;
@Override
public Connection getConnection() throws SQLException {
String currentDbName = getCurrentDbName();
if(CommonConstants.DEFAULT_DB.equals(currentDbName)){
Connection connection = defaultDataSource.getConnection();
connection.setCatalog(currentDbName);
return connection;
}
Connection connection = this.determineTargetDataSource().getConnection();
connection.setCatalog(currentDbName);
return connection;
}
@Override
public Connection getConnection(String username, String password) throws SQLException {
String currentDbName = getCurrentDbName();
if(CommonConstants.DEFAULT_DB.equals(currentDbName)){
Connection connection = defaultDataSource.getConnection();
connection.setCatalog(currentDbName);
return connection;
}
Connection connection = this.determineTargetDataSource().getConnection(username, password);
connection.setCatalog(getCurrentDbName());
return connection;
}
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
return iface.isInstance(this) ? (T) this : this.determineTargetDataSource().unwrap(iface);
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return iface.isInstance(this) || this.determineTargetDataSource().isWrapperFor(iface);
}
protected DataSource determineTargetDataSource() {
DataSource dataSource = null;
Map<String, DataSource> resolvedDataSources = dynamicDataSourceService.getResolvedDataSources();
if (resolvedDataSources != null) {
String lookupKey = getDbServerByDbName();
if (StringUtils.isNotBlank(lookupKey)) {
dataSource = resolvedDataSources.get(lookupKey);
}
}
if (dataSource == null) {
dataSource = defaultDataSource;
}
return dataSource;
}
/**
* 通过dbName获取dbServer
*
* @return
*/
protected String getDbServerByDbName() {
String dbName = getCurrentDbName();
return dynamicDataSourceService.getDbServerByDbName(dbName);
}
/**
* 查询当前线程上下文对应的库名
*
* @return
*/
protected String getCurrentDbName() {
String dbName = DataSourceContext.getDataSourceType();
if (StringUtils.isBlank(dbName)) {
dbName = CommonConstants.DEFAULT_DB;
}
return dbName;
}
}

View File

@@ -1,130 +0,0 @@
package com.cool.store.config.datasource;
import com.cool.store.constants.CommonConstants;
import com.cool.store.utils.RedisUtilPool;
import com.cool.store.context.DataSourceContext;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.sql.DataSource;
import java.text.MessageFormat;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
/**
* @ClassName DynamicDataSourceServiceImpl
* @Description 用一句话描述什么
*/
@Service
@Slf4j
public class DynamicDataSourceServiceImpl {
private static int defaultMaxPoolSize = 150;
private static String dbUrl = "jdbc:mysql://{0}:{1}/coolcollege_intelligent_config?useSSL=false&useUnicode=true&characterEncoding=utf8&allowMultiQueries=true&autoReconnect=true";
@Autowired
private RedisUtilPool redisUtilPool;
@Autowired
private MyHikariConfig myHikariConfig;
@Autowired
private EnterpriseConfigService enterpriseConfigService;
/**
* 数据库实例和数据源的映射
*/
private ConcurrentHashMap<String, DataSource> resolvedDataSources = new ConcurrentHashMap();
/**
* dbName 和 serverUrl的映射
*/
private ConcurrentHashMap<String, String> dbNameUrlServerMap = new ConcurrentHashMap();
/**
* 查询所有的企业数据库实例节点配置信息
*
* @return
*/
public List<DatasourceInfoDTO> getDbNodes() {
List<EnterpriseConfigDO> configList = enterpriseConfigService.getDistinctDbServer();
return DatasourceInfoDTO.convertList(configList);
}
/**
* 根据dbName查询dbServer
*
* @param dbName
* @return
*/
public String getDbServerByDbName(String dbName) {
if(CommonConstants.DEFAULT_DB.equals(dbName)){
return null;
}
String dbServerUrl = dbNameUrlServerMap.get(dbName);
if(StringUtils.isBlank(dbServerUrl)){
Page<Object> localPage = PageHelper.getLocalPage();
if(Objects.nonNull(localPage)){
PageHelper.clearPage();
}
String currentDbName = DataSourceContext.getDataSourceType();
EnterpriseConfigDO config = enterpriseConfigService.getDbInfoByDbName(dbName);
dbServerUrl = config.getDbServer();
if(StringUtils.isNotBlank(currentDbName)){
DataSourceContext.setDataSourceType(currentDbName);
}
if(Objects.nonNull(localPage)){
//上下文中的东西及时还回去
PageHelper.startPage(localPage.getPageNum(), localPage.getPageSize());
}
dbNameUrlServerMap.put(dbName, dbServerUrl);
}
return dbServerUrl;
}
public void createDataSource(DatasourceInfoDTO datasource) {
DataSource dataSource = buildDataSourceByConfig(datasource);
if (dataSource != null) {
this.resolvedDataSources.putIfAbsent(datasource.getDbServer(), dataSource);
}
}
public Map<String, DataSource> getResolvedDataSources() {
return resolvedDataSources;
}
/**
* build datasource
* @param dbServerUrl
* @return
*/
private DataSource buildDataSourceByConfig(DatasourceInfoDTO datasource) {
HikariConfig hikariConfig = new HikariConfig();
String url = MessageFormat.format(dbUrl, datasource.getDbServer(), String.valueOf(datasource.getDbPort()));
hikariConfig.setDriverClassName(myHikariConfig.getDriverClassName());
hikariConfig.setMinimumIdle(myHikariConfig.getMinimumIdle());
hikariConfig.setMaximumPoolSize(myHikariConfig.getMaximumPoolSize());
hikariConfig.setMaxLifetime(myHikariConfig.getMaxLifetime());
hikariConfig.setConnectionTimeout(myHikariConfig.getConnectionTimeout());
hikariConfig.setIdleTimeout(myHikariConfig.getIdleTimeout());
hikariConfig.setJdbcUrl(url);
hikariConfig.setUsername(datasource.getDbUser());
hikariConfig.setPassword(datasource.getDbPwd());
hikariConfig.setMaximumPoolSize(defaultMaxPoolSize);
String poolName = "HikariCP_" + datasource.getDbServer();
hikariConfig.setPoolName(poolName);
HikariDataSource hikariDataSource = new HikariDataSource(hikariConfig);
log.info("{} dataSource is {}, maxPoolSize={}", poolName, hikariDataSource, hikariDataSource.getMaximumPoolSize());
return hikariDataSource;
}
}

View File

@@ -1,10 +0,0 @@
package com.cool.store.config.datasource;
import com.zaxxer.hikari.HikariConfig;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties("spring.datasource.hikari")
public class MyHikariConfig extends HikariConfig {
}