思路

  1. yml中配置多个数据源信息
  2. 通过AOP切换不同数据源
  3. 配合mybatis plus使用

POM依赖

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter</artifactId>
  4. </dependency>
  5. <!-- AOP依赖 -->
  6. <dependency>
  7. <groupId>org.springframework.boot</groupId>
  8. <artifactId>spring-boot-starter-aop</artifactId>
  9. </dependency>
  10. <dependency>
  11. <groupId>org.mybatis.spring.boot</groupId>
  12. <artifactId>mybatis-spring-boot-starter</artifactId>
  13. <version>2.0.0</version>
  14. </dependency>
  15. <!-- MyBatisPlus -->
  16. <dependency>
  17. <groupId>com.baomidou</groupId>
  18. <artifactId>mybatis-plus-boot-starter</artifactId>
  19. <version>3.1.0</version>
  20. </dependency>
  21. <!--Mysql-->
  22. <dependency>
  23. <groupId>mysql</groupId>
  24. <artifactId>mysql-connector-java</artifactId>
  25. <version>5.1.6</version>
  26. <scope>runtime</scope>
  27. </dependency>
  28. <!-- Druid依赖 -->
  29. <dependency>
  30. <groupId>com.alibaba</groupId>
  31. <artifactId>druid-spring-boot-starter</artifactId>
  32. <version>1.1.10</version>
  33. </dependency>

YML配置

  1. spring:
  2. aop:
  3. proxy-target-class: true
  4. auto: true
  5. datasource:
  6. druid:
  7. es:
  8. url: jdbc:mysql://192.168.21.181:3306/jarvis
  9. username: root
  10. password: 123456
  11. type: com.alibaba.druid.pool.DruidDataSource
  12. driver-class-name: com.mysql.jdbc.Driver
  13. initialSize: 5
  14. minIdle: 5
  15. maxActive: 20
  16. wx:
  17. initialSize: 5
  18. minIdle: 5
  19. maxActive: 20
  20. type: com.alibaba.druid.pool.DruidDataSource
  21. driver-class-name: com.mysql.jdbc.Driver
  22. username: root
  23. password: 123456
  24. url: jdbc:mysql://192.168.21.181:3306/jarvis_wx

启动加载多个数据源

  1. package com.jarvis.config;
  2.  
  3. import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
  4. import com.baomidou.mybatisplus.core.MybatisConfiguration;
  5. import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
  6. import com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor;
  7. import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
  8. import org.apache.ibatis.plugin.Interceptor;
  9. import org.apache.ibatis.session.SqlSessionFactory;
  10. import org.apache.ibatis.type.JdbcType;
  11. import org.mybatis.spring.annotation.MapperScan;
  12. import org.springframework.beans.factory.annotation.Qualifier;
  13. import org.springframework.boot.context.properties.ConfigurationProperties;
  14. import org.springframework.context.annotation.Bean;
  15. import org.springframework.context.annotation.Configuration;
  16. import org.springframework.context.annotation.Primary;
  17. import org.springframework.transaction.annotation.EnableTransactionManagement;
  18.  
  19. import javax.sql.DataSource;
  20. import java.util.HashMap;
  21. import java.util.Map;
  22.  
  23. @Configuration
  24. @EnableTransactionManagement
  25. @MapperScan("com.jarvis.task.*.mapper")
  26. public class MybatisPlusConfig {
  27.  
  28. /***
  29. * plus 的性能优化
  30. */
  31. @Bean
  32. public PerformanceInterceptor performanceInterceptor() {
  33. PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
  34. /* <!-- SQL 执行性能分析,开发环境使用,线上不推荐。 maxTime 指的是 sql 最大执行时长 --> */
  35. //performanceInterceptor.setMaxTime(1000);
  36. /* <!--SQL是否格式化 默认false--> */
  37. performanceInterceptor.setFormat(false);
  38. return performanceInterceptor;
  39. }
  40.  
  41. /**
  42. * mybatis-plus 分页插件
  43. */
  44. @Bean
  45. public PaginationInterceptor paginationInterceptor() {
  46. PaginationInterceptor page = new PaginationInterceptor();
  47. page.setDialectType("mysql");
  48. return page;
  49. }
  50.  
  51. @Bean(name = "esDb")
  52. @ConfigurationProperties(prefix = "spring.datasource.druid.es" )
  53. public DataSource esDb () {
  54. return DruidDataSourceBuilder.create().build();
  55. }
  56.  
  57. @Bean(name = "wxDb")
  58. @ConfigurationProperties(prefix = "spring.datasource.druid.wx" )
  59. public DataSource wxDb () {
  60. return DruidDataSourceBuilder.create().build();
  61. }
  62. /**
  63. * 动态数据源配置
  64. * @return
  65. */
  66. @Bean
  67. @Primary
  68. public DataSource multipleDataSource (@Qualifier("esDb") DataSource esDb,
  69. @Qualifier("wxDb") DataSource wxDb ) {
  70. DynamicDataSource dynamicDataSource = new DynamicDataSource();
  71. Map< Object, Object > targetDataSources = new HashMap<>(2);
  72. targetDataSources.put(DBTypeEnum.ES.getValue(), esDb );
  73. targetDataSources.put(DBTypeEnum.WX.getValue(), wxDb);
  74. dynamicDataSource.setTargetDataSources(targetDataSources);
  75. dynamicDataSource.setDefaultTargetDataSource(esDb);
  76. return dynamicDataSource;
  77. }
  78.  
  79. @Bean("sqlSessionFactory")
  80. public SqlSessionFactory sqlSessionFactory() throws Exception {
  81. MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
  82. sqlSessionFactory.setDataSource(multipleDataSource(esDb(),wxDb()));
  83. //sqlSessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:/mapper/*/*Mapper.xml"));
  84.  
  85. MybatisConfiguration configuration = new MybatisConfiguration();
  86. //configuration.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class);
  87. configuration.setJdbcTypeForNull(JdbcType.NULL);
  88. configuration.setMapUnderscoreToCamelCase(true);
  89. configuration.setCacheEnabled(false);
  90. sqlSessionFactory.setConfiguration(configuration);
  91. sqlSessionFactory.setPlugins(new Interceptor[]{ //PerformanceInterceptor(),OptimisticLockerInterceptor()
  92. paginationInterceptor() //添加分页功能
  93. });
  94. // sqlSessionFactory.setGlobalConfig(globalConfiguration());
  95. return sqlSessionFactory.getObject();
  96. }
  97.  
  98. // @Bean
  99. // public GlobalConfiguration globalConfiguration() {
  100. // GlobalConfiguration conf = new GlobalConfiguration(new LogicSqlInjector());
  101. // conf.setLogicDeleteValue("-1");
  102. // conf.setLogicNotDeleteValue("1");
  103. // conf.setIdType(0);
  104. // conf.setMetaObjectHandler(new MyMetaObjectHandler());
  105. // conf.setDbColumnUnderline(true);
  106. // conf.setRefresh(true);
  107. // return conf;
  108. // }
  109. }

DBType枚举类

  1. public enum DBTypeEnum {
  2. ES("es"), WX("wx");
  3. private String value;
  4.  
  5. DBTypeEnum(String value) {
  6. this.value = value;
  7. }
  8.  
  9. public String getValue() {
  10. return value;
  11. }
  12. }

动态数据源决策

  1. import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
  2.  
  3. public class DynamicDataSource extends AbstractRoutingDataSource {
  4. /**
  5. * 取得当前使用哪个数据源
  6. * @return
  7. */
  8. @Override
  9. protected Object determineCurrentLookupKey() {
  10. return DbContextHolder.getDbType();
  11. }
  12. }

设置、获取数据源

  1. public class DbContextHolder {
  2. private static final ThreadLocal contextHolder = new ThreadLocal<>();
  3. /**
  4. * 设置数据源
  5. * @param dbTypeEnum
  6. */
  7. public static void setDbType(DBTypeEnum dbTypeEnum) {
  8. contextHolder.set(dbTypeEnum.getValue());
  9. }
  10.  
  11. /**
  12. * 取得当前数据源
  13. * @return
  14. */
  15. public static String getDbType() {
  16. return (String) contextHolder.get();
  17. }
  18.  
  19. /**
  20. * 清除上下文数据
  21. */
  22. public static void clearDbType() {
  23. contextHolder.remove();
  24. }
  25. }

AOP实现的数据源切换

  1. import lombok.extern.slf4j.Slf4j;
  2. import org.aspectj.lang.annotation.*;
  3. import org.springframework.core.annotation.Order;
  4. import org.springframework.stereotype.Component;
  5.  
  6. @Component
  7. @Aspect
  8. @Order(-100) //这是为了保证AOP在事务注解之前生效,Order的值越小,优先级越高
  9. @Slf4j
  10. public class DataSourceSwitchAspect {
  11.  
  12. @Pointcut("execution(* com.jarvis.task.db2es.mapper..*.*(..))")
  13. private void jarvisAspect() {
  14. }
  15.  
  16. @Pointcut("execution(* com.jarvis.task.dt2db.mapper..*.*(..))")
  17. private void jarvisWxAspect() {
  18. }
  19.  
  20. @Before("jarvisAspect()")
  21. public void jarvisDb() {
  22. log.info("切换到ES 数据源...");
  23. DbContextHolder.setDbType(DBTypeEnum.ES);
  24. }
  25.  
  26. @Before("jarvisWxAspect()")
  27. public void jarvisWxDb () {
  28. log.info("切换到WX 数据源...");
  29. DbContextHolder.setDbType(DBTypeEnum.WX);
  30. }
  31. }

mapper层结构

参考

  https://www.jianshu.com/p/ff5af6c59365?utm_source=oschina-app

springboot+druid+mybatis plus的多数据源配置的更多相关文章

  1. 2019-04-09 SpringBoot+Druid+MyBatis+Atomikos 的多数据源配置

    前面部分是网上找的,我按照网上写的把自己搭建的过程展示一次 1.引入依赖 目前项目本来使用到了Mybatis plus(在自己的Mapper接口中继承BaseMapper获得基本的CRUD,而不需要增 ...

  2. Spring Boot 入门系列(二十三)整合Mybatis,实现多数据源配置!

    d之前介绍了Spring Boot 整合mybatis 使用注解方式配置的方式实现增删改查以及一些复杂自定义的sql 语句 .想必大家对spring boot 项目中,如何使用mybatis 有了一定 ...

  3. springboot+druid+mybatis

    pom.xml <dependency> <groupId>com.microsoft.sqlserver</groupId> <artifactId> ...

  4. springboot v2.0.3版本多数据源配置

    本篇分享的是springboot多数据源配置,在从springboot v1.5版本升级到v2.0.3时,发现之前写的多数据源的方式不可用了,捕获错误信息如: 异常:jdbcUrl is requir ...

  5. Spring Boot + Mybatis多数据源和动态数据源配置

    文章转自 https://blog.csdn.net/neosmith/article/details/61202084 网上的文章基本上都是只有多数据源或只有动态数据源,而最近的项目需要同时使用两种 ...

  6. spring+mybatis最简多数据源配置

    作者:纯洁的微笑出处:http://www.ityouknow.com/ 版权所有,欢迎保留原文链接进行转载:) 说起多数据源,一般都来解决那些问题呢,主从模式或者业务比较复杂需要连接不同的分库来支持 ...

  7. springboot系列十、springboot整合redis、多redis数据源配置

    一.简介 Redis 的数据库的整合在 java 里面提供的官方工具包:jedis,所以即便你现在使用的是 SpringBoot,那么也继续使用此开发包. 二.redidTemplate操作 在 Sp ...

  8. SSM框架、Druid连接池实现多数据源配置(已上线使用)

    总体大概流程: 1.配置数据源.账密(账密一致,文章不多阐述) driverClassName = com.mysql.jdbc.Driver   validationQuery = SELECT 1 ...

  9. springboot+Druid+mybatis整合

    一.添加Druid.MySQL连接池.mybatis依赖 <!--整合Druid--> <dependency> <groupId>com.alibaba</ ...

随机推荐

  1. ubuntu docker中crontab任务不执行的问题

    problem of task of crontab in docker of ubuntu do not working! 由于各种原因,要在Ubuntu docker上部署crontab任务,如 ...

  2. Java面试题之“==”和“equals()”方法的区别?

    一.“== ”:运算符 1.可以使用在基本数据类型变量和引用数据类型变量中. 2.如果比较的是基本数据类型变量:比较的是两个变量保存的数据是否相等.(不一定类型要相同) 3.如果比较的是引用数据类型变 ...

  3. LwIP与IPv6

    2.0.0中才开始支持IPv6,在此版本中改写了SNMP,但还没有IPv6的统计量.目前最新版本是2.0.2,其中SNMP也没有IPv6统计量(哪些?与IP的统计量有何区别?) 1.4.1中虽然有ip ...

  4. docker-enter 安装

    github : https://github.com/sequenceiq/docker-enter [root@localhost ~]# docker run --rm -v /usr/loca ...

  5. 大数四则运算之减法运算-----c语言版

    /* 分三种情况: 1.减数长度大于被减数 交换减数与被减数,输出负号,方便减 2.减数长度等于被减数(分三种情况) a.减数大于被减数,类似1情况1 b.减数等于被减数,两数相等,直接输出0,完成. ...

  6. hexo--定制开发

    新建页面 hexo new page "新建博文章的名称" 这时会在工程的source目录下新建about目录,里面新建index.md 在主题的_configy.yml中配置新页 ...

  7. 记网站部署中一个奇葩BUG

    网页中引用的文件名不要带 adv 等 近日在写好一个网页后就把他部署到apache上测试,结果用chrome访问时有个背景图片总显示不出来,但是用firefox等却一切正常, 关键是我用windows ...

  8. Redis-位图

    关于位图,可能大家不太熟悉, 那么位图能干啥呢?位图的内容其实就是普通的字符串,也就是byte数组,我们都知道 byte 8 位无符号整数 0 到 255 说个场景.比如你处理一些业务时候,往往会存在 ...

  9. 【React Native】在网页中打开Android应用程序

    React Native官方提供Linking库用于调起其他app或者本机应用.Linking的主要属性和方法有: 属性与方法 canOpenURL(url); 判断设备上是否有已经安装相应应用或可以 ...

  10. Android中动态改变Listview中字体的颜色

    效果如下: 账目显示用的是Listview,要实现的功能为使其根据所在Item是“收入”还是“支出”来把数字设置成绿色或红色 方法是自定义适配器,并重写其中getView()函数,实现如下: //自定 ...