关于MybatisPlus配置双数据库驱动连接数据库问题

 更新时间:2022年1月22日 12:40  点击:312 作者:chaojunma

最近项目中需要用到2种数据库驱动连接数据库,下面我们基于MybatisPlus实现一下

具体实现

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数据源配置
      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 数据源配置
      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.StdOutImpl

3、新建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 {
 
    // 默认数据源
    public static final String DEFAULT_DS = DataSourceEnum.DB1.getValue();
 
    private static final ThreadLocal<String> contextHolder = new InheritableThreadLocal<>();
 
    /**
     *  设置数据源
     * @param db
     */
    public static void setDataSource(String db){
        contextHolder.set(db);
    }
 
    /**
     * 取得当前数据源
     * @return
     */
    public static String getDataSource(){
        return contextHolder.get();
    }
 
    /**
     * 清除上下文数据
     */
    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("切换到数据源[{}]", dataSource.value().getValue());
        DataSourceContextHolder.setDataSource(dataSource.value().getValue());
    }
 
    @After("@within(dataSource)")
    public void doAfter(JoinPoint point, DataSource dataSource){
        log.info("回收数据源[{}]", 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("切换到数据源[{}]", dataSource.value().getValue());
        DataSourceContextHolder.setDataSource(dataSource.value().getValue());
    }
 
    @After("@annotation(dataSource)")
    public void doAfter(JoinPoint point, DataSource dataSource){
        log.info("回收数据源[{}]", dataSource.value().getValue());
        DataSourceContextHolder.clear();
    }
}

8、新建多数据源配置类,如下:

@Configuration
@MapperScan("com.dms.gateway.api.mapper")
public class MybatisPlusConfig {
 
    /*
     * 分页插件,自动识别数据库类型
     * 多租户,请参考官网【插件扩展】
     */
    @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();
    }
 
    /**
     * 动态数据源配置
     * @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);
        //添加数据源
        multipleDataSource.setTargetDataSources(targetDataSources);
        //设置默认数据源
        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();
    }
}

接下来需要具体的业务逻辑,在service层的类或者方法上面添加@DataSource注解来指定该业务需要用到的数据源,如下:

@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));
    }
 
}

启动服务,调用相关的接口,我们会在控制台看到如下信息:

说明数据源切换成功!!!

到此这篇关于关于MybatisPlus配置双数据库驱动连接数据库问题的文章就介绍到这了,更多相关MybatisPlus配置双数据库内容请搜索猪先飞以前的文章或继续浏览下面的相关文章希望大家以后多多支持猪先飞!

原文出处:https://blog.csdn.net/chaojunma/article/details/122616950

[!--infotagslink--]

相关文章

  • MyBatisPlus-QueryWrapper多条件查询及修改方式

    这篇文章主要介绍了MyBatisPlus-QueryWrapper多条件查询及修改方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2022-06-27
  • MybatisPlus实现逻辑删除功能

    这篇文章主要介绍了MybatisPlus实现逻辑删除功能,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-12-25
  • 解决mybatisplus插入报错argument type mismatch的问题

    这篇文章主要介绍了解决mybatisplus插入报错argument type mismatch的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-11-25
  • MybatisPlus实现分页查询和动态SQL查询的示例代码

    本文主要介绍了MybatisPlus实现分页查询和动态SQL查询的示例代码,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-09-30
  • Vue数据驱动模拟实现4

    这篇文章主要介绍了Vue数据驱动模拟实现的相关资料,介绍了Array的变异方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2017-01-16
  • Maven中央仓库正式成为Oracle官方JDBC驱动程序组件分发中心(推荐)

    这篇文章主要介绍了Maven中央仓库正式成为Oracle官方JDBC驱动程序组件分发中心,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2020-12-08
  • deepin20 安装英伟达闭源驱动的步骤详解

    这篇文章主要介绍了deepin20 安装英伟达闭源驱动的步骤,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2020-09-09
  • 详解Javascript事件驱动编程

    这篇文章主要为大家详细介绍了Javascript事件驱动编程的相关资料,通过经典案例向大家介绍Javascript事件驱动编程,需要的朋友可以参考下...2016-01-07
  • C#中使用1.7版本驱动操作MongoDB简单例子

    这篇文章主要介绍了C#中使用1.7版本驱动操作MongoDB简单例子,本文给出了连接MongoDB、操作MongoDB数据等例子,需要的朋友可以参考下...2020-06-25
  • 一篇超详细的SpringBoot整合MybatisPlus的文章

    这篇文章主要介绍了springboot整合Mybatis-plus的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-07-27
  • 用PHP和MySQL构建一个数据库驱动的网站(四)

    摘要   在这一章中,我们将介绍PHP这个服务器端的脚本语言。我们将会看到,这个语言可以很好地支持与MySQL数据库的通信。 (2002-08-29 14:10:52) --------------------...2016-11-25
  • springboot+mybatis plus实现树形结构查询

    实际开发过程中经常需要查询节点树,根据指定节点获取子节点列表,本文主要介绍了springboot+mybatis plus实现树形结构查询,感兴趣的可以了解一下...2021-07-22
  • 详解Vue 事件驱动和依赖追踪

    本篇文章主要介绍了详解Vue 事件驱动和依赖追踪 ,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧 ...2017-04-27
  • js事件驱动机制 浏览器兼容处理方法

    下面小编就为大家带来一篇js事件驱动机制 浏览器兼容处理方法。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2016-07-29
  • 用PHP和MySQL构建一个数据库驱动的网站(三)

    摘要   在这一章,我们将集中学习如何使用结构化查询语言(SQL)在MySQL数据库中工作。 (2002-08-29 14:11:10) ------------------------------------------------------...2016-11-25
  • C#判断指定驱动器是否已经准备就绪的方法

    这篇文章主要介绍了C#判断指定驱动器是否已经准备就绪的方法,涉及C#针对硬件IO操作的技巧,需要的朋友可以参考下...2020-06-25
  • 用PHP和MySQL构建一个数据库驱动的网站(7)

    现在我们已经有了允许用户输入一个笑话并将其加入到我们的数据库中的程序代码。现在剩下的就是将其加入到我们已做好的笑话显示页面。因为绝大多数的用户只会想要看看...2016-11-25
  • 用PHP和MySQL构建一个数据库驱动的网站(八)

    摘要   在这一章中,我们会对我们的例子进行扩充,学习一些有关MySQL的新知识,并试图理解并掌握关系型数据库所能提供的功能。 (2002-08-29 14:11:39) -----------------...2016-11-25
  • SpringBoot+MyBatisPlus+MySQL8实现树形结构查询

    这篇文章主要为大家详细介绍了SpringBoot+MyBatisPlus+MySQL8实现树形结构查询,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-06-07
  • Java静态代码块加载驱动代码实例

    这篇文章主要介绍了Java静态代码块加载驱动代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下...2020-07-15