This commit is contained in:
zhangchenbiao
2023-06-06 17:32:47 +08:00
parent 7a78f59ad7
commit 2d0d896a58
46 changed files with 343 additions and 4400 deletions

View File

@@ -22,9 +22,6 @@ import javax.sql.DataSource;
*/
@SpringBootApplication
@MapperScan("com.cool.store.mapper")
@EnableAsync
@EnableCaching
@ServletComponentScan
public class PartnerBWebApplication {
public static void main(String[] args) {

View File

@@ -1,40 +0,0 @@
package com.cool.store.config;
import com.alibaba.fastjson.JSONObject;
import com.cool.store.config.datasource.DynamicDataSourceServiceImpl;
import com.cool.store.dto.DatasourceInfoDTO;
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
* @Description:
* @date 2023-05-19 18:41
*/
@Slf4j
@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,109 +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.beans.factory.annotation.Value;
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;
@Value("${default.database.name:coolcollege_intelligent_config}")
private String defaultDb;
@Override
public Connection getConnection() throws SQLException {
String currentDbName = getCurrentDbName();
if(defaultDb.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(defaultDb.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 = defaultDb;
}
return dbName;
}
}

View File

@@ -1,135 +0,0 @@
package com.cool.store.config.datasource;
import com.cool.store.constants.CommonConstants;
import com.cool.store.dto.DatasourceInfoDTO;
import com.cool.store.entity.EnterpriseConfigDO;
import com.cool.store.service.EnterpriseConfigService;
import com.cool.store.utils.DataSourceHelper;
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.beans.factory.annotation.Value;
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}/{2}?useSSL=false&useUnicode=true&characterEncoding=utf8&allowMultiQueries=true&autoReconnect=true";
@Autowired
private RedisUtilPool redisUtilPool;
@Autowired
private MyHikariConfig myHikariConfig;
@Autowired
private EnterpriseConfigService enterpriseConfigService;
@Value("${default.database.name:coolcollege_intelligent_config}")
private String defaultDb;
/**
* 数据库实例和数据源的映射
*/
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(defaultDb.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();
DataSourceHelper.reset();
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()), datasource.getDbName());
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 {
}

View File

@@ -1,10 +1,12 @@
package com.cool.store.controller;
import com.cool.store.entity.EnterpriseConfigDO;
import com.cool.store.entity.EnterpriseUserDO;
import com.cool.store.enums.RocketMqTagEnum;
import com.cool.store.http.ISVHttpRequest;
import com.cool.store.mq.producer.SimpleMessageService;
import com.cool.store.response.ResponseResult;
import com.cool.store.service.EnterpriseConfigService;
import com.cool.store.service.EnterpriseUserService;
import com.cool.store.utils.UUIDUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
@@ -13,6 +15,7 @@ import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.List;
/**
* @author zhangchenbiao
@@ -27,6 +30,10 @@ public class TestController {
@Resource
private SimpleMessageService simpleMessageService;
@Resource
private EnterpriseUserService enterpriseUserService;
@Resource
private ISVHttpRequest isvHttpRequest;
@GetMapping("/sendMq")
public ResponseResult sendMq(){
@@ -36,4 +43,55 @@ public class TestController {
return ResponseResult.success();
}
@GetMapping("getUserInfo")
public ResponseResult getUserInfo(@RequestParam("userId")String userId){
EnterpriseUserDO enterpriseUser = enterpriseUserService.getUserInfoByUserId(userId);
return ResponseResult.success(enterpriseUser);
}
@GetMapping("getUserIdByCode")
public ResponseResult getUserIdByCode(@RequestParam("paramStr")String paramStr){
return ResponseResult.success(isvHttpRequest.getUserIdByCode(paramStr));
}
@GetMapping("getUserDetailByUserId")
public ResponseResult getUserDetailByUserId(@RequestParam("userId")String userId){
return ResponseResult.success(isvHttpRequest.getUserDetailByUserId(userId));
}
@GetMapping("getAdminUserList")
public ResponseResult getAdminUserList(){
return ResponseResult.success(isvHttpRequest.getAdminUserList());
}
@GetMapping("getAuthInfo")
public ResponseResult getAuthInfo(){
return ResponseResult.success(isvHttpRequest.getAuthInfo());
}
@GetMapping("getDepartments")
public ResponseResult getDepartments(@RequestParam("parentId")String parentId){
return ResponseResult.success(isvHttpRequest.getDepartments(parentId));
}
@GetMapping("getAuthScope")
public ResponseResult getAuthScope(){
return ResponseResult.success(isvHttpRequest.getAuthScope());
}
@GetMapping("getDepartmentUsers")
public ResponseResult getDepartmentUsers(@RequestParam("deptId")String deptId){
return ResponseResult.success(isvHttpRequest.getDepartmentUsers(deptId));
}
@GetMapping("getUserDetailByUserIds")
public ResponseResult getUserDetailByUserIds(@RequestParam("userIds") List<String> userIds){
return ResponseResult.success(isvHttpRequest.getUserDetailByUserIds(userIds));
}
@GetMapping("getSubDepartments")
public ResponseResult getSubDepartments(@RequestParam("parentId")String parentId, @RequestParam("fetchChild")Boolean fetchChild){
return ResponseResult.success(isvHttpRequest.getSubDepartments(parentId, fetchChild));
}
}

View File

@@ -36,7 +36,7 @@ customize_sub_table_size=10
mybatis.configuration.call-setters-on-nulls=true
mybatis.configuration.map-underscore-to-camel-case=true
isv.domain = https://abstore-isv.coolstore.cn
isv.domain = http://localhost:31100
#rocketmq \u914D\u7F6E
rocketmq.accessKey=zK2oVEz4G1ts23d2