欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-06-17 17:35:20
最近项目中需要用到2种数据库驱动连接数据库,下面我们基于mybatisplus实现一下具体实现1、在pom.xml中添加如下依赖:

最近项目中需要用到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配置双数据库驱动连接数据库问题的文章就介绍到这了,更多相关mybatisplus配置双数据库内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!