功能说明
实现springboot+mybatisplus项目中,动态切换数据库连接及实现类的简易方案。实现效果为:1.将数据源连接信息动态维护到数据表中(可以通过页面实时维护到表中);2. 在线选择数据源就可以实时切换数据库连接及实现,以达到真动态切换数据库的目录。
使用示例说明
参照ddb-sample模块,详细代码参见:https://gitee.com/llfsnial/snail-component-library
-
依赖
<dependencies><!-- 这个就是主要的启动类 --><dependency><groupId>com.snail</groupId><artifactId>ddb-spring-boot-starter</artifactId><version>1.0-SNAPSHOT</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId><version>2.7.18</version></dependency><!-- MySQL驱动 --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.27</version></dependency><dependency><groupId>com.oracle</groupId><artifactId>ojdbc6</artifactId><version>11.2.0.3</version></dependency><!-- mybatisPlus 核心库 --><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.5.3.2</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.2.22</version></dependency></dependencies><!-- 主要为了解决依赖冲突的问题 --><dependencyManagement><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-dependencies</artifactId><version>2.7.18</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement>
-
配置
server:port: 8786 spring:datasource:dynamic:# 这个druid必须配置.druid:initial-size: 5min-idle: 5maxActive: 20maxWait: 60000timeBetweenEvictionRunsMillis: 60000minEvictableIdleTimeMillis: 300000validationQuery: SELECT 1 FROM DUALtestWhileIdle: truetestOnBorrow: falsetestOnReturn: falsepoolPreparedStatements: truemaxPoolPreparedStatementPerConnectionSize: 20filters: stat,wall,slf4jprimary: master # 这个是默认的数据库连接.datasource:master:url: jdbc:mysql://xxxx:3306/xxxx?characterEncoding=UTF-8&useUnicode=true&useSSL=false&tinyInt1isBit=false&allowPublicKeyRetrieval=true&serverTimezone=Asia/Shanghaiusername: xxxpassword: xxxxdriver-class-name: com.mysql.cj.jdbc.Driverhikari:connection-test-query: SELECT 1minimum-idle: 5maximum-pool-size: 15max-lifetime: 1800000connection-timeout: 20000idle-timeout: 180000 mybatis-plus:mapper-locations: classpath:/com/sanil/sample/ddb/mapper/xml/*Mapper.xmlglobal-config:db-config:id-type: autofield-strategy: NOT_EMPTYdb-type: MYSQLconfiguration:map-underscore-to-camel-case: truecall-setters-on-nulls: truelog-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 打开这个两个可以看那个configuration未匹配上。 logging:level:org.springframework.boot.autoconfigure: DEBUGorg.springframework.context.annotation: DEBUG
-
提供DataSourceInfoProvider的实现
public class CommonController implements DataSourceInfoProvider {@Overridepublic DataSourceInfo getDataSourceInfo(String dataSourceId) {SysDataSource sysDataSource = getDynamicDbSourceById(dataSourceId);DataSourceInfo dataSourceInfo = new DataSourceInfo();dataSourceInfo.setDbType(Integer.parseInt(sysDataSource.getDbType()));dataSourceInfo.setUrl(sysDataSource.getDbUrl());dataSourceInfo.setUsername(sysDataSource.getDbUsername());dataSourceInfo.setPassword(sysDataSource.getDbPassword());dataSourceInfo.setDriverClassName(sysDataSource.getDbDriver());dataSourceInfo.setId(sysDataSource.getId());return dataSourceInfo;} }
-
提供DynamicDataBase的实现
@RestController @RequestMapping("/dds/dbInfo/") @Slf4j public class DynamicDataBaseController implements DynamicDataBase {@Autowiredprivate IDbInfoService dbInfoService;@GetMapping("getDbNameList")public Result getDbNameList(String dsName) {Result<List<String>> result = new Result<>();try {List<String> allDataBaseName = dbInfoService.getAllDbName(dsName);result.setSuccess(true);result.setResult(allDataBaseName);return result;} catch (Exception e) {log.error(e.getMessage(), e);result.setSuccess(false);result.setMessage(String.format("查询失败:%s", e.getLocalizedMessage()));}return result;}@Overridepublic void setDataBaseOperator(DataBaseOperator dataBaseOperator) {dbInfoService.setDataBaseOperator(dataBaseOperator);} }
-
提供多个DataBaseOperator的实现
public interface DbInfoMapper extends DataBaseOperator {List<String> queryAllDbName(String dsName);
}public interface SqlServerDbInfoMapper extends DbInfoMapper {default String getDataBaseType() {return DataBaseTypeRep.getDataBaseType(3).getTypeId();}
}
public interface OracleDbInfoMapper extends DbInfoMapper {default String getDataBaseType(){return DataBaseTypeRep.getDataBaseType(2).getTypeId();};
}
public interface MysqlDbInfoMapper extends DbInfoMapper {default String getDataBaseType(){return DataBaseTypeRep.getDataBaseType(4).getTypeId();};
}