關(guān)于MybatisPlus配置雙數(shù)據(jù)庫驅(qū)動連接數(shù)據(jù)庫問題
最近項(xiàng)目中需要用到2種數(shù)據(jù)庫驅(qū)動連接數(shù)據(jù)庫,下面我們基于MybatisPlus實(shí)現(xiàn)一下
具體實(shí)現(xiàn)
1、在pom.xml中添加如下依賴:
<properties>
<java.version>1.8</java.version>
<lombok.version>1.18.2</lombok.version>
<mybatis-plus.version>3.2.0</mybatis-plus.version>
<druid.version>1.1.9</druid.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- postgrepsql-->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatis-plus.version}</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>${mybatis-plus.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>${druid.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
</dependencies>2、在yml配置文件中添加如下配置:
server:
port: 8080
spring:
application:
name: xxxx
datasource:
druid:
# mysql數(shù)據(jù)源配置
db1:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/db1?useUnicode=true&characterEncoding=UTF-8&useSSL=false
username: ${username}
password: ${password}
initial-size: 5
min-idle: 5
max-active: 50
# postgresql 數(shù)據(jù)源配置
db2:
driver-class-name: org.postgresql.Driver
url: jdbc:postgresql://127.0.0.1:5432/db2?useUnicode=true&characterEncoding=utf-8
username: ${username}
password: ${password}
initial-size: 5
min-idle: 5
max-active: 50
# mybatis-plus配置
mybatis-plus:
type-aliases-package: com.dms.gateway.api.entity
mapper-locations: classpath:/mapper/*Mapper.xml
global-config:
db-config:
id-type: auto
field-strategy: not_empty
logic-delete-value: 1
logic-not-delete-value: 0
configuration:
map-underscore-to-camel-case: true
cache-enabled: false
call-setters-on-nulls: true
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl3、新建DataSourceEnum枚舉類,如下:
public enum DataSourceEnum {
DB1("db1"),
DB2("db2");
private String value;
DataSourceEnum(String value){this.value=value;}
public String getValue() {
return value;
}
}4、新建DataSourceContextHolder類,如下:
public class DataSourceContextHolder {
// 默認(rèn)數(shù)據(jù)源
public static final String DEFAULT_DS = DataSourceEnum.DB1.getValue();
private static final ThreadLocal<String> contextHolder = new InheritableThreadLocal<>();
/**
* 設(shè)置數(shù)據(jù)源
* @param db
*/
public static void setDataSource(String db){
contextHolder.set(db);
}
/**
* 取得當(dāng)前數(shù)據(jù)源
* @return
*/
public static String getDataSource(){
return contextHolder.get();
}
/**
* 清除上下文數(shù)據(jù)
*/
public static void clear(){
contextHolder.remove();
}
}5、新建MultipleDataSource類,如下:
public class MultipleDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return DataSourceContextHolder.getDataSource();
}
}6、新建DataSource注解,如下:
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DataSource {
DataSourceEnum value() default DataSourceEnum.DB1;
}7、新建面向類和方法級別的切面,如下:
@Component
@Slf4j
@Aspect
@Order(-6)
public class DataSourceClassAspect {
@Before("@within(dataSource)")
public void doBefore(JoinPoint point, DataSource dataSource){
log.info("切換到數(shù)據(jù)源[{}]", dataSource.value().getValue());
DataSourceContextHolder.setDataSource(dataSource.value().getValue());
}
@After("@within(dataSource)")
public void doAfter(JoinPoint point, DataSource dataSource){
log.info("回收數(shù)據(jù)源[{}]", dataSource.value().getValue());
DataSourceContextHolder.clear();
}
}
@Component
@Slf4j
@Aspect
@Order(-5)
public class DataSourceMethodAspect {
@Before("@annotation(dataSource)")
public void doBefore(JoinPoint point, DataSource dataSource){
log.info("切換到數(shù)據(jù)源[{}]", dataSource.value().getValue());
DataSourceContextHolder.setDataSource(dataSource.value().getValue());
}
@After("@annotation(dataSource)")
public void doAfter(JoinPoint point, DataSource dataSource){
log.info("回收數(shù)據(jù)源[{}]", dataSource.value().getValue());
DataSourceContextHolder.clear();
}
}8、新建多數(shù)據(jù)源配置類,如下:
@Configuration
@MapperScan("com.dms.gateway.api.mapper")
public class MybatisPlusConfig {
/*
* 分頁插件,自動識別數(shù)據(jù)庫類型
* 多租戶,請參考官網(wǎng)【插件擴(kuò)展】
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
return paginationInterceptor;
}
@Bean(name = "db1")
@ConfigurationProperties(prefix = "spring.datasource.druid.db1" )
public DataSource db1() {
return DruidDataSourceBuilder.create().build();
}
@Bean(name = "db2")
@ConfigurationProperties(prefix = "spring.datasource.druid.db2" )
public DataSource db2() {
return DruidDataSourceBuilder.create().build();
}
/**
* 動態(tài)數(shù)據(jù)源配置
* @return
*/
@Bean
@Primary
public DataSource multipleDataSource(@Qualifier("db1") DataSource db1,
@Qualifier("db2") DataSource db2) {
MultipleDataSource multipleDataSource = new MultipleDataSource();
Map< Object, Object > targetDataSources = new HashMap<>();
targetDataSources.put(DataSourceEnum.DB1.getValue(), db1);
targetDataSources.put(DataSourceEnum.DB2.getValue(), db2);
//添加數(shù)據(jù)源
multipleDataSource.setTargetDataSources(targetDataSources);
//設(shè)置默認(rèn)數(shù)據(jù)源
multipleDataSource.setDefaultTargetDataSource(db1);
return multipleDataSource;
}
@Bean("sqlSessionFactory")
public SqlSessionFactory sqlSessionFactory() throws Exception {
MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
sqlSessionFactory.setDataSource(multipleDataSource(db1(),db2()));
MybatisConfiguration configuration = new MybatisConfiguration();
configuration.setJdbcTypeForNull(JdbcType.NULL);
configuration.setMapUnderscoreToCamelCase(true);
configuration.setCacheEnabled(false);
sqlSessionFactory.setConfiguration(configuration);
//添加分頁功能
sqlSessionFactory.setPlugins(paginationInterceptor());
return sqlSessionFactory.getObject();
}
}接下來需要具體的業(yè)務(wù)邏輯,在service層的類或者方法上面添加@DataSource注解來指定該業(yè)務(wù)需要用到的數(shù)據(jù)源,如下:
@Service
@DataSource(DataSourceEnum.DB2)
public class GatewayLogService {
@Autowired
private GatewayLogMapper mapper;
@Override
public Result<IPage<GatewayLog>> pageList(GatewayLogDTO gatewayLogDTO) {
LambdaQueryWrapper<GatewayLog> wrapper = Wrappers.lambdaQuery();
wrapper.like(StringUtils.isNotEmpty(gatewayLogDTO.getPath()), GatewayLog::getPath, gatewayLogDTO.getPath());
wrapper.like(StringUtils.isNotEmpty(gatewayLogDTO.getSourceServer()), GatewayLog::getSourceServer, gatewayLogDTO.getSourceServer());
wrapper.like(StringUtils.isNotEmpty(gatewayLogDTO.getTargetServer()), GatewayLog::getTargetServer, gatewayLogDTO.getTargetServer());
wrapper.eq(StringUtils.isNotEmpty(gatewayLogDTO.getMethod()), GatewayLog::getMethod, gatewayLogDTO.getMethod());
wrapper.like(StringUtils.isNotEmpty(gatewayLogDTO.getRequestBody()), GatewayLog::getRequestBody, gatewayLogDTO.getRequestBody());
wrapper.like(StringUtils.isNotEmpty(gatewayLogDTO.getResponse()), GatewayLog::getResponse, gatewayLogDTO.getResponse());
wrapper.orderByDesc(GatewayLog::getId);
IPage<GatewayLog> page = new Page<>(gatewayLogDTO.getPageNo(), gatewayLogDTO.getPageSize());
return Result.success(mapper.selectPage(page, wrapper));
}
}啟動服務(wù),調(diào)用相關(guān)的接口,我們會在控制臺看到如下信息:

說明數(shù)據(jù)源切換成功!?。?/p>
到此這篇關(guān)于關(guān)于MybatisPlus配置雙數(shù)據(jù)庫驅(qū)動連接數(shù)據(jù)庫問題的文章就介紹到這了,更多相關(guān)MybatisPlus配置雙數(shù)據(jù)庫內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Idea如何導(dǎo)入一個SpringBoot項(xiàng)目的方法(圖文教程)
這篇文章主要介紹了Idea如何導(dǎo)入一個SpringBoot項(xiàng)目的方法(圖文教程),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09

