SpringBoot+Mybatis plus实现多数据源整合的实践
程序员文章站
2022-01-20 06:08:27
springboot 版本为1.5.10.release,mybatis plus 版本为2.1.8。第一步:填写配置信息:spring: aop: proxy-target-class: t...
springboot 版本为1.5.10.release,mybatis plus 版本为2.1.8。
第一步:填写配置信息:
spring: aop: proxy-target-class: true auto: true datasource: druid: # 数据库 1 db1: url: jdbc:mysql://localhost:3306/db1?useunicode=true&characterencoding=utf8&autoreconnect=true&zerodatetimebehavior=converttonull&transformedbitisboolean=true username: root password: root driver-class-name: com.mysql.jdbc.driver initialsize: 5 minidle: 5 maxactive: 20 # 数据库 2 db2: url: jdbc:mysql://localhost:3306/db2?useunicode=true&characterencoding=utf8&autoreconnect=true&zerodatetimebehavior=converttonull&transformedbitisboolean=true username: root password: root driver-class-name: com.mysql.jdbc.driver initialsize: 5 minidle: 5 maxactive: 20
第二步: 数据源配置:
@configuration @mapperscan({"com.warm.system.mapper*"}) public class mybatisplusconfig { /** * mybatis-plus分页插件<br> * 文档:http://mp.baomidou.com<br> */ @bean public paginationinterceptor paginationinterceptor() { paginationinterceptor paginationinterceptor = new paginationinterceptor(); //paginationinterceptor.setlocalpage(true);// 开启 pagehelper 的支持 return paginationinterceptor; } /** * mybatis-plus sql执行效率插件【生产环境可以关闭】 */ @bean public performanceinterceptor performanceinterceptor() { return new performanceinterceptor(); } @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 ) { dynamicdatasource dynamicdatasource = new dynamicdatasource(); map< object, object > targetdatasources = new hashmap<>(); targetdatasources.put(dbtypeenum.db1.getvalue(), db1 ); targetdatasources.put(dbtypeenum.db2.getvalue(), db2); dynamicdatasource.settargetdatasources(targetdatasources); dynamicdatasource.setdefaulttargetdatasource(db1); return dynamicdatasource; } @bean("sqlsessionfactory") public sqlsessionfactory sqlsessionfactory() throws exception { mybatissqlsessionfactorybean sqlsessionfactory = new mybatissqlsessionfactorybean(); sqlsessionfactory.setdatasource(multipledatasource(db1(),db2())); //sqlsessionfactory.setmapperlocations(new pathmatchingresourcepatternresolver().getresources("classpath:/mapper/*/*mapper.xml")); mybatisconfiguration configuration = new mybatisconfiguration(); //configuration.setdefaultscriptinglanguage(mybatisxmllanguagedriver.class); configuration.setjdbctypefornull(jdbctype.null); configuration.setmapunderscoretocamelcase(true); configuration.setcacheenabled(false); sqlsessionfactory.setconfiguration(configuration); sqlsessionfactory.setplugins(new interceptor[]{ //performanceinterceptor(),optimisticlockerinterceptor() paginationinterceptor() //添加分页功能 }); sqlsessionfactory.setglobalconfig(globalconfiguration()); return sqlsessionfactory.getobject(); } @bean public globalconfiguration globalconfiguration() { globalconfiguration conf = new globalconfiguration(new logicsqlinjector()); conf.setlogicdeletevalue("-1"); conf.setlogicnotdeletevalue("1"); conf.setidtype(0); conf.setmetaobjecthandler(new mymetaobjecthandler()); conf.setdbcolumnunderline(true); conf.setrefresh(true); return conf; } }
第三步:利用aop进行数据源的动态切换:
@component @aspect @order(-100) //这是为了保证aop在事务注解之前生效,order的值越小,优先级越高 @slf4j public class datasourceswitchaspect { @pointcut("execution(* com.warm.system.service.db1..*.*(..))") private void db1aspect() { } @pointcut("execution(* com.warm.system.service.db2..*.*(..))") private void db2aspect() { } @before( "db1aspect()" ) public void db1() { log.info("切换到db1 数据源..."); dbcontextholder.setdbtype(dbtypeenum.db1); } @before("db2aspect()" ) public void db2 () { log.info("切换到db2 数据源..."); dbcontextholder.setdbtype(dbtypeenum.db2); } } public class dbcontextholder { private static final threadlocal contextholder = new threadlocal<>(); /** * 设置数据源 * @param dbtypeenum */ public static void setdbtype(dbtypeenum dbtypeenum) { contextholder.set(dbtypeenum.getvalue()); } /** * 取得当前数据源 * @return */ public static string getdbtype() { return (string) contextholder.get(); } /** * 清除上下文数据 */ public static void cleardbtype() { contextholder.remove(); } } public enum dbtypeenum { db1("db1"), db2("db2"); private string value; dbtypeenum(string value) { this.value = value; } public string getvalue() { return value; } } public class dynamicdatasource extends abstractroutingdatasource { /** * 取得当前使用哪个数据源 * @return */ @override protected object determinecurrentlookupkey() { return dbcontextholder.getdbtype(); } }
ok!写个单元测试来验证一下:
@springboottest @runwith(springjunit4classrunner.class) public class datatest { @autowired private userservice userservice; @autowired private orderservice orderservice; @test public void test() { userservice.getuserlist().stream().foreach(item -> system.out.println(item)); orderservice.getorderlist().stream().foreach(item -> system.out.println(item)); } }
如图所示,证明数据源能动态切换了。
具体项目结构和代码参考github。
踩坑记录:
直接调用mybatis plus 的service方法aop不会生效,即数据源不会动态切换,解决方法:在自己的service层中封装一下,调用自定义的service方法aop即能正常生效了,如下所示:
@service public class userserviceimpl extends serviceimpl<usermapper, user> implements userservice { @override public list<user> getuserlist() { return selectlist(null); } }
application.yml 定义的mybatis plus 配置信息不生效,如:
#mybatis mybatis-plus: mapper-locations: classpath:/mapper/*/*mapper.xml #实体扫描,多个package用逗号或者分号分隔 typealiasespackage: com.jinhuatuo.edu.sys.entity global-config: #主键类型 0:"数据库id自增", 1:"用户输入id",2:"全局唯一id (数字类型唯一id)", 3:"全局唯一id uuid"; id-type: 0 #字段策略 0:"忽略判断",1:"非 null 判断"),2:"非空判断" field-strategy: 2 #驼峰下划线转换 db-column-underline: true #刷新mapper 调试神器 refresh-mapper: true #数据库大写下划线转换 #capital-mode: true #序列接口实现类配置 #key-generator: com.baomidou.springboot.xxx #逻辑删除配置 #logic-delete-value: 0 #logic-not-delete-value: 1 #自定义填充策略接口实现 meta-object-handler: com.jinhuatuo.edu.config.mybatis.mymetaobjecthandler #自定义sql注入器 #sql-injector: com.baomidou.springboot.xxx configuration: map-underscore-to-camel-case: true cache-enabled: false
解决方法: 所有这些配置在mybatisplusconfig 类中用代码的方式进行配置,分页插件亦是如此,否则统计列表总数的数据会拿不到,参考代码即可。
在application.yml配置
logging: level: debug
控制台也不会打印mybatis 执行的sql语句,解决方法:自定义日志输出方案,如在classpath下直接引入日志配置文件如logback-spring.xml即可,同时application.yml无需再配置日志信息。
logback-spring.xml配置参考:
<?xml version="1.0" encoding="utf-8"?> <!-- scan:配置文件如果发生改变,将会重新加载,默认值为true --> <configuration scan="true" scanperiod="10 seconds"> <!-- <include resource="org/springframework/boot/logging/logback/base.xml"/> --> <!-- 日志文件路径 --> <!-- <springproperty name="logfilepath" source="logging.path"/> --> <property resource="application.yml" /> <substitutionproperty name="log_home" value="${logging.path}" /> <substitutionproperty name="project_name" value="${spring.application.name}" /> <!--<substitutionproperty name="cur_node" value="${info.node}" />--> <!-- 日志数据库路径 --> <!-- <springproperty name="logdbpath" source="spring.datasource.one.url"/> <springproperty name="logdbdriver" source="spring.datasource.one.driver-class-name"/> <springproperty name="logdbuser" source="spring.datasource.one.username"/> <springproperty name="logdbpwd" source="spring.datasource.one.password"/> --> <!-- 将日志文件 --> <appender name="file" class="ch.qos.logback.core.rolling.rollingfileappender"> <append>true</append> <encoder> <pattern> [ %-5level] [%date{yyyy-mm-dd hh:mm:ss}] %logger{96} [%line] - %msg%n </pattern> <charset>utf-8</charset> </encoder> <rollingpolicy class="ch.qos.logback.core.rolling.timebasedrollingpolicy"> <filenamepattern>${log_home}/${project_name}-%d{yyyy-mm-dd}.%i.log</filenamepattern> <timebasedfilenamingandtriggeringpolicy class="ch.qos.logback.core.rolling.sizeandtimebasedfnatp"> <maxfilesize>50 mb</maxfilesize> </timebasedfilenamingandtriggeringpolicy> <!--最多保留30天log--> <maxhistory>30</maxhistory> </rollingpolicy> </appender> <!-- 将日志错误文件--> <appender name="file_error" class="ch.qos.logback.core.rolling.rollingfileappender"> <append>true</append> <encoder> <pattern> [ %-5level] [%date{yyyy-mm-dd hh:mm:ss}] %logger{96} [%line] - %msg%n </pattern> <charset>utf-8</charset> </encoder> <rollingpolicy class="ch.qos.logback.core.rolling.timebasedrollingpolicy"> <filenamepattern>${log_home}/${project_name}-error-%d{yyyy-mm-dd}.%i.log</filenamepattern> <timebasedfilenamingandtriggeringpolicy class="ch.qos.logback.core.rolling.sizeandtimebasedfnatp"> <maxfilesize>50 mb</maxfilesize> </timebasedfilenamingandtriggeringpolicy> <!--最多保留30天log--> <maxhistory>30</maxhistory> </rollingpolicy> <filter class="ch.qos.logback.classic.filter.thresholdfilter"> <level>error</level> <!-- <onmatch>accept</onmatch> <onmismatch>deny </onmismatch> --> </filter> </appender> <!-- 将日志写入控制台 --> <appender name="console" class="ch.qos.logback.core.consoleappender"> <encoder> <pattern> [ %-5level] [%date{yyyy-mm-dd hh:mm:ss}] %logger{96} [%line] - %msg%n </pattern> <!--<charset>utf-8</charset>--> </encoder> </appender> <!-- 将日志写入数据库 --> <!-- <appender name="db-classic-mysql-pool" class="ch.qos.logback.classic.db.dbappender"> <connectionsource class="ch.qos.logback.core.db.datasourceconnectionsource"> <datasource class="org.springframework.jdbc.datasource.drivermanagerdatasource"> <driverclassname>${logdbdriver}</driverclassname> <url>${logdbpath}</url> <username>${logdbuser}</username> <password>${logdbpwd}</password> </datasource> </connectionsource> </appender> --> <!-- spring扩展,分环境配置log信息 --> <springprofile name="dev"> <!-- <logger name="sand.dao" level="debug"/> --> <!-- <logger name="org.springframework.web" level="info"/> --> <logger name="org.springboot.sample" level="trace" /> <logger name="org.springframework.cloud" level="info" /> <logger name="com.netflix" level="info"></logger> <logger name="org.springframework.boot" level="info"></logger> <logger name="org.springframework.web" level="info"/> <logger name="jdbc.sqltiming" level="debug"/> <logger name="com.ibatis" level="debug" /> <logger name="com.ibatis.common.jdbc.simpledatasource" level="debug" /> <logger name="com.ibatis.common.jdbc.scriptrunner" level="debug" /> <logger name="com.ibatis.sqlmap.engine.impl.sqlmapclientdelegate" level="debug" /> <logger name="java.sql.connection" level="debug" /> <logger name="java.sql.statement" level="debug" /> <logger name="java.sql.preparedstatement" level="debug" /> <logger name="java.sql.resultset" level="debug" /> <logger name="com.warm" level="debug"/> <root level="debug"> <appender-ref ref="console" /> <appender-ref ref="file" /> </root> <root level="error"> <appender-ref ref="file_error" /> <!-- <appender-ref ref="db-classic-mysql-pool" /> --> </root> </springprofile> <springprofile name="test"> <logger name="org.springboot.sample" level="trace" /> <logger name="org.springframework.cloud" level="info" /> <logger name="com.netflix" level="info"></logger> <logger name="org.springframework.boot" level="info"></logger> <logger name="org.springframework.web" level="info"/> <logger name="jdbc.sqltiming" level="debug"/> <logger name="com.ibatis" level="debug" /> <logger name="com.ibatis.common.jdbc.simpledatasource" level="debug" /> <logger name="com.ibatis.common.jdbc.scriptrunner" level="debug" /> <logger name="com.ibatis.sqlmap.engine.impl.sqlmapclientdelegate" level="debug" /> <logger name="java.sql.connection" level="debug" /> <logger name="java.sql.statement" level="debug" /> <logger name="java.sql.preparedstatement" level="debug" /> <logger name="java.sql.resultset" level="debug" /> <logger name="com.warm" level="debug"/> <root level="debug"> <!-- <appender-ref ref="console" /> --> <appender-ref ref="file" /> </root> <root level="error"> <appender-ref ref="file_error" /> <!-- <appender-ref ref="db-classic-mysql-pool" /> --> </root> </springprofile> <springprofile name="prod"> <logger name="org.springboot.sample" level="trace" /> <logger name="org.springframework.cloud" level="info" /> <logger name="com.netflix" level="info"></logger> <logger name="org.springframework.boot" level="info"></logger> <logger name="org.springframework.web" level="info"/> <logger name="jdbc.sqltiming" level="debug"/> <logger name="com.ibatis" level="debug" /> <logger name="com.ibatis.common.jdbc.simpledatasource" level="debug" /> <logger name="com.ibatis.common.jdbc.scriptrunner" level="debug" /> <logger name="com.ibatis.sqlmap.engine.impl.sqlmapclientdelegate" level="debug" /> <logger name="java.sql.connection" level="debug" /> <logger name="java.sql.statement" level="debug" /> <logger name="java.sql.preparedstatement" level="debug" /> <logger name="java.sql.resultset" level="debug" /> <logger name="com.warm" level="info"/> <root level="debug"> <!-- <appender-ref ref="console" /> --> <appender-ref ref="file" /> </root> <root level="error"> <appender-ref ref="file_error" /> <!-- <appender-ref ref="db-classic-mysql-pool" /> --> </root> </springprofile> </configuration>
到此这篇关于springboot+mybatis plus实现多数据源整合的实践的文章就介绍到这了,更多相关springboot+mybatis plus多数据源内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
下一篇: oracle给新项目建表实操