最近项目中需要用到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配置文件中添加如下配置:
rver: port: 8080 spring: application: name: xxxx datasource: druid: # mysql数据源配置 db1: driver-class-name: com.mysql.jdbc.driver url: jdbc:mysq华硕笔记本键盘报价l://127.0.0.1:3306/db1?uunicode=true&characterencoding=utf-8&ussl=fal urname: ${urname} 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?uunicode=true&characterencoding=utf-8 urname: ${urname} password: ${password} initial-size: 5 min-idle: 5 max-active: 50 # mybatis-plus配置mybatis-plus: type-alias-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-ca: true cache-enabled: fal call-tters-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 tdatasource(string db){ contextholder.t(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)@documentedpublic @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.tdatasource(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.tdatasource(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.ttargetdatasources(targetdatasources); //设置默认数据源 multipledatasource.tdefaulttargetdatasource(db1); return multipledatasource; } @bean("sqlssionfactory") public sqlssionfactory sqlssionfactory() throws exception { mybatissqlssionfactorybean sqlssionfactory = new mybatissqlssionfactorybean(); sqlss比较容易唱的歌ionfactory.tdatasource(multipledatasource(db1(),db2())); mybatisconfiguration configuration = new mybatisconfiguration(); configuration.tjdbctypefornull(jdbctype.null); configuration.tmapunderscoretocamelca(true); configuration.tcacheenabled(fal); sqlssionfactory.tconfiguration(configuration); //添加分页功能 sqlssionfactory.tplugins(paginationinterceptor()); return sqlssionfactory.getobject(); }}
接下来需要具体的业务逻辑,在rvice层的类或者方法上面添加@datasource
注解来指定该业务需要用到的数据源,如下:
@rvice@datasource(datasourceenum.db2)public class gatewaylogrvice { @autowired private gatewaylogmapper mapper; @override public result<ipage<gatewaylog>> pagelist(gatewaylogdto gatewaylogdto) { lambdaquerywrapper<gatewaylog> wrapper = wrappers.lambdaquery(); wrapper.like(stringutils.isnotempty(gat团队拓展训练ewaylogdto.getpath()), gatewaylog::getpath, gatewaylogdto.getpath()); wrapper.like(stringutils.isnotempty(gatewaylogdto.getsourcerver()), gatewaylog::getsourcerver, gatewaylogdto.getsourcerver()); wrapper.like(stringutils.isnotempty(gatewaylogdto.gettargetrver()), gatewaylog::gettargetrver, gatewaylogdto.gettargetrver()); 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.getrespon()), gatewaylog::getrespon, gatewaylogdto.getrespon()); wrapper.orderbydesc(gatewaylog::getid); ipage<gatewaylog> page = new page<>(gatewaylogdto.getpageno(), gatewaylogdto.getpagesize()); return result.success(mapper.lectpage(page, wrapper)); } }
启动服务,调用相关的接口,我们会在控制台看到如下信息:
说明数据源切换成功!!!
到此这篇关于关于mybatisplus配置双数据库驱动连接数据库问题的文章就介绍到这了,更多相关mybatisplus配置双数据库内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.c李维嘉回应筷子门om!
本文发布于:2023-04-04 17:15:26,感谢您对本站的认可!
本文链接:https://www.wtabcd.cn/fanwen/zuowen/5cc88303b5788b84b2aa458a90e31b82.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文word下载地址:关于MybatisPlus配置双数据库驱动连接数据库问题.doc
本文 PDF 下载地址:关于MybatisPlus配置双数据库驱动连接数据库问题.pdf
留言与评论(共有 0 条评论) |