springboot+druid+mybatis plus的多数据源配置
思路
- yml中配置多个数据源信息
- 通过AOP切换不同数据源
- 配合mybatis plus使用
POM依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- AOP依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
<!-- MyBatisPlus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.1.0</version>
</dependency>
<!--Mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
<scope>runtime</scope>
</dependency>
<!-- Druid依赖 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
YML配置
spring:
aop:
proxy-target-class: true
auto: true
datasource:
druid:
es:
url: jdbc:mysql://192.168.21.181:3306/jarvis
username: root
password: 123456
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
initialSize: 5
minIdle: 5
maxActive: 20
wx:
initialSize: 5
minIdle: 5
maxActive: 20
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
username: root
password: 123456
url: jdbc:mysql://192.168.21.181:3306/jarvis_wx
启动加载多个数据源
package com.jarvis.config; import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.type.JdbcType;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.transaction.annotation.EnableTransactionManagement; import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map; @Configuration
@EnableTransactionManagement
@MapperScan("com.jarvis.task.*.mapper")
public class MybatisPlusConfig { /***
* plus 的性能优化
*/
@Bean
public PerformanceInterceptor performanceInterceptor() {
PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
/* <!-- SQL 执行性能分析,开发环境使用,线上不推荐。 maxTime 指的是 sql 最大执行时长 --> */
//performanceInterceptor.setMaxTime(1000);
/* <!--SQL是否格式化 默认false--> */
performanceInterceptor.setFormat(false);
return performanceInterceptor;
} /**
* mybatis-plus 分页插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor page = new PaginationInterceptor();
page.setDialectType("mysql");
return page;
} @Bean(name = "esDb")
@ConfigurationProperties(prefix = "spring.datasource.druid.es" )
public DataSource esDb () {
return DruidDataSourceBuilder.create().build();
} @Bean(name = "wxDb")
@ConfigurationProperties(prefix = "spring.datasource.druid.wx" )
public DataSource wxDb () {
return DruidDataSourceBuilder.create().build();
}
/**
* 动态数据源配置
* @return
*/
@Bean
@Primary
public DataSource multipleDataSource (@Qualifier("esDb") DataSource esDb,
@Qualifier("wxDb") DataSource wxDb ) {
DynamicDataSource dynamicDataSource = new DynamicDataSource();
Map< Object, Object > targetDataSources = new HashMap<>(2);
targetDataSources.put(DBTypeEnum.ES.getValue(), esDb );
targetDataSources.put(DBTypeEnum.WX.getValue(), wxDb);
dynamicDataSource.setTargetDataSources(targetDataSources);
dynamicDataSource.setDefaultTargetDataSource(esDb);
return dynamicDataSource;
} @Bean("sqlSessionFactory")
public SqlSessionFactory sqlSessionFactory() throws Exception {
MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
sqlSessionFactory.setDataSource(multipleDataSource(esDb(),wxDb()));
//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;
// }
}
DBType枚举类
public enum DBTypeEnum {
ES("es"), WX("wx");
private String value;
DBTypeEnum(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
动态数据源决策
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
public class DynamicDataSource extends AbstractRoutingDataSource {
/**
* 取得当前使用哪个数据源
* @return
*/
@Override
protected Object determineCurrentLookupKey() {
return DbContextHolder.getDbType();
}
}
设置、获取数据源
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();
}
}
AOP实现的数据源切换
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.*;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component; @Component
@Aspect
@Order(-100) //这是为了保证AOP在事务注解之前生效,Order的值越小,优先级越高
@Slf4j
public class DataSourceSwitchAspect { @Pointcut("execution(* com.jarvis.task.db2es.mapper..*.*(..))")
private void jarvisAspect() {
} @Pointcut("execution(* com.jarvis.task.dt2db.mapper..*.*(..))")
private void jarvisWxAspect() {
} @Before("jarvisAspect()")
public void jarvisDb() {
log.info("切换到ES 数据源...");
DbContextHolder.setDbType(DBTypeEnum.ES);
} @Before("jarvisWxAspect()")
public void jarvisWxDb () {
log.info("切换到WX 数据源...");
DbContextHolder.setDbType(DBTypeEnum.WX);
}
}
mapper层结构

参考
https://www.jianshu.com/p/ff5af6c59365?utm_source=oschina-app
springboot+druid+mybatis plus的多数据源配置的更多相关文章
- 2019-04-09 SpringBoot+Druid+MyBatis+Atomikos 的多数据源配置
前面部分是网上找的,我按照网上写的把自己搭建的过程展示一次 1.引入依赖 目前项目本来使用到了Mybatis plus(在自己的Mapper接口中继承BaseMapper获得基本的CRUD,而不需要增 ...
- Spring Boot 入门系列(二十三)整合Mybatis,实现多数据源配置!
d之前介绍了Spring Boot 整合mybatis 使用注解方式配置的方式实现增删改查以及一些复杂自定义的sql 语句 .想必大家对spring boot 项目中,如何使用mybatis 有了一定 ...
- springboot+druid+mybatis
pom.xml <dependency> <groupId>com.microsoft.sqlserver</groupId> <artifactId> ...
- springboot v2.0.3版本多数据源配置
本篇分享的是springboot多数据源配置,在从springboot v1.5版本升级到v2.0.3时,发现之前写的多数据源的方式不可用了,捕获错误信息如: 异常:jdbcUrl is requir ...
- Spring Boot + Mybatis多数据源和动态数据源配置
文章转自 https://blog.csdn.net/neosmith/article/details/61202084 网上的文章基本上都是只有多数据源或只有动态数据源,而最近的项目需要同时使用两种 ...
- spring+mybatis最简多数据源配置
作者:纯洁的微笑出处:http://www.ityouknow.com/ 版权所有,欢迎保留原文链接进行转载:) 说起多数据源,一般都来解决那些问题呢,主从模式或者业务比较复杂需要连接不同的分库来支持 ...
- springboot系列十、springboot整合redis、多redis数据源配置
一.简介 Redis 的数据库的整合在 java 里面提供的官方工具包:jedis,所以即便你现在使用的是 SpringBoot,那么也继续使用此开发包. 二.redidTemplate操作 在 Sp ...
- SSM框架、Druid连接池实现多数据源配置(已上线使用)
总体大概流程: 1.配置数据源.账密(账密一致,文章不多阐述) driverClassName = com.mysql.jdbc.Driver validationQuery = SELECT 1 ...
- springboot+Druid+mybatis整合
一.添加Druid.MySQL连接池.mybatis依赖 <!--整合Druid--> <dependency> <groupId>com.alibaba</ ...
随机推荐
- Mac安装Mysql-python遇到的坑,被这俩报错反复摩擦:'my_config.h' file not found 和 IndexError: string index out of range
最后Stackoverflow上面的大神解决了问题: Link brew install mysql brew unlink mysql brew install mysql-connector-c ...
- VFP执行 SQL Server 储存过程示例
PUBLIC errvalPUBLIC errmsgPUBLIC handleerrval=0errmsg=' ' *Sql Server 连接参数sourcename= 'test'user= 's ...
- 排查 Kubernetes HPA 通过 Prometheus 获取不到 http_requests 指标的问题
部署好了 kube-prometheus 与 k8s-prometheus-adapter (详见之前的博文 k8s 安装 prometheus 过程记录),使用下面的配置文件部署 HPA(Horiz ...
- Java也疯狂-分享利用ffmpeg做视频转换的工具
朋友需要经常将视频统一转换为mp4格式,市面上的工具很多,但是转换的体积.自动化程度等都不好,于是花了一个小时给朋友写了个给予ffmpeg的批量转换工具,功能简单但是很实用,也正好给学习Java的同学 ...
- Android Webview H5资源本地化
Android Webview H5资源本地化 一. 创建读取资源项目独立模块 1. 项目依赖的好处 符合模块化的思想,他们相互独立.一个项目持有另一个项目的引用,修改更加方便. (注:compile ...
- Hexo | 超详细的hexo+githhub page搭建过程
首先安装node.js 安装git 去Git官网根据你的电脑参数,下载对应版本. 下载完成,通过在命令行输入 git version 查看是否安装成功,有输出版本号说明安装成功. 鼠标邮件菜单里就多了 ...
- JS-重写内置的call、apply、bind
首先看call和apply,第一个参数就是改变的this指向,写谁就是谁,如果是非严格模式下,传递null或undefined指向的也是window,二者唯一的区别是执行函数时,传递的参数方式不同,c ...
- Android 有关在ListView RecycleView 中使用EditText Checkbox的坑
这是一篇文字超多的博客,哈哈哈,废话自行过滤··· 遇到问题 在开发中我们常会在ListView , RecycleView 列表中添加EditText输入框,或者checkbox复选框. 复选框 ...
- MongoDB集群负载不均衡问题定位及解决
1.问题描述 这是一套运行在腾讯云上的MongoDB 3.6版本集群,共5个分片,每片规格是6核16GB. 在压测的过程中,发现第3个分片的CPU使用率长时间高达96%,其它4个分片的CPU使用率都没 ...
- IIS网站部署配置
1.配置Session State