springboot整合druid连接池、mybatis实现多数据源动态切换
demo环境:
JDK 1.8 ,Spring boot 1.5.14
一 整合durid
1.添加druid连接池maven依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.29</version>
</dependency>
2.配置多数据源Druid
- 2.1 application.yml关于数据源配置
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
master:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/db_test?characterEncoding=utf-8&autoReconnect=true&failOverReadOnly=false
username: root
password: root
# 连接池初始化大小
initialSize: 5
# 配置获取连接等待超时的时间
maxWait: 60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
timeBetweenEvictionRunsMillis: 60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
minEvictableIdleTimeMillis: 30000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
# 打开PSCache,并且指定每个连接上PSCache的大小
poolPreparedStatements: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
# 合并多个DruidDataSource的监控数据
useGlobalDataSourceStat: true
filters: stat,wall,log4j
slave:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/db_slave?characterEncoding=utf-8&autoReconnect=true&failOverReadOnly=false
username: root
password: root
# 连接池初始化大小
initialSize: 5
# 配置获取连接等待超时的时间
maxWait: 60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
timeBetweenEvictionRunsMillis: 60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
minEvictableIdleTimeMillis: 30000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
# 打开PSCache,并且指定每个连接上PSCache的大小
poolPreparedStatements: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
# 合并多个DruidDataSource的监控数据
useGlobalDataSourceStat: true
filters: stat,wall,log4
PS:若不配置filters在druid的SQL监控无法正常打印(如果选择的maven是直接继承springboot的druid-spring-boot-starter就不需要配置)
- 2.2 多数据源Bean的配置以及动态数据源的实现
@Configuration
@EnableTransactionManagement
public class DataSourceConfig {
@Value("${spring.datasource.type}")
private Class<? extends DataSource> dataSourceType; @Bean(name = "dbMasterDataSource")
@ConfigurationProperties(prefix = "spring.datasource.master")
public DataSource dbTestDataSource(){
return DataSourceBuilder.create().type(dataSourceType).build();
} @Bean(name = "dbSlaveDataSource")
@ConfigurationProperties(prefix = "spring.datasource.slave")
public DataSource dbSlaveDataSource(){
return DataSourceBuilder.create().type(dataSourceType).build();
} @Bean(name = "dataSource")
@Primary
public AbstractRoutingDataSource dataSource(){
MasterSlaveRoutingDataSource masterSlaveRoutingDataSource = new MasterSlaveRoutingDataSource();
Map<Object, Object> targetDataResources = new HashMap<>();
// targetDataResources.put(DbContextHolder.DbType.MASTER, dbTestDataSource());
// targetDataResources.put(DbContextHolder.DbType.SLAVE, dbSlaveDataSource());
targetDataResources.put(DbEnum.MASTER, dbTestDataSource());
targetDataResources.put(DbEnum.SLAVE, dbSlaveDataSource());
masterSlaveRoutingDataSource.setDefaultTargetDataSource(dbSlaveDataSource());
masterSlaveRoutingDataSource.setTargetDataSources(targetDataResources);
masterSlaveRoutingDataSource.afterPropertiesSet();
return masterSlaveRoutingDataSource;
}
}
@Bean(name = "***")配置了两个数据源,将AbstractRoutingDataSource永@Primary注解标注,表示这个动态数据源是首选数据源
- 2.3 druid页面监控台配置
@WebFilter(filterName = "druidWebStatFilter", urlPatterns = "/*", initParams = {@WebInitParam(name = "exclusions", value = "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*")})
public class DruidStatFilter extends WebStatFilter {
}
3.整合mybatis
- 3.1 mybatis配置文件
mybatis:
mapper-locations: classpath*:/mapper/*.xml
check-config-location: true
type-aliases-package: com.springboot.datasource.entity
config-location: classpath:mybatis-config.xml
pagehelper:
auto-dialect: true
close-conn: false
reasonable: true
helperDialect: mysql
supportMethodsArguments: true
params: count=countSql
4.切面注解配置
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface DynamicDb {
String value() default DbEnum.MASTER;
}
@Aspect
@Component
public class DbAspect implements Ordered {
private static final Logger logger = LoggerFactory.getLogger(DbAspect.class); @Before("@annotation(masterDb)")
public void beforeSwitch(JoinPoint joinPoint, MasterDb masterDb){
System.out.println("进入之前");
} @Around("@annotation(masterDb)")
public Object proceed(ProceedingJoinPoint proceedingJoinPoint, MasterDb masterDb) throws Throwable{
try {
logger.info("set database connection to db_test only");
DbContextHolder.setDbType(DbContextHolder.DbType.MASTER);
Object result = proceedingJoinPoint.proceed();
return result;
}finally {
DbContextHolder.clearDbType();
logger.info("restore database connection");
}
} @Around("@annotation(slaveDb)")
public Object proceed(ProceedingJoinPoint proceedingJoinPoint, SlaveDb slaveDb) throws Throwable{
try {
logger.info("set database connection to db_test only");
DbContextHolder.setDbType(DbContextHolder.DbType.SLAVE);
Object result = proceedingJoinPoint.proceed();
return result;
}finally {
DbContextHolder.clearDbType();
logger.info("restore database connection");
}
}
@Around("@annotation(dynamicDb)")
public Object proceed(ProceedingJoinPoint proceedingJoinPoint, DynamicDb dynamicDb) throws Throwable{
try {
logger.info("set database connection to {} only",dynamicDb.value());
DbContextHolder.setDb(dynamicDb.value());
Object result = proceedingJoinPoint.proceed();
return result;
}finally {
DbContextHolder.clearDb();
logger.info("restore database connection");
}
} @Override
public int getOrder() {
return 0;
}
}
5. 启动主程序
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
@ServletComponentScan
@EnableAspectJAutoProxy
public class BootDatasourceApplication {
public static void main(String[] args) {
SpringApplication.run(BootDatasourceApplication.class, args);
}
}
按网上的需要将@MapperScan 加入到BootDatasourceApplication 类用来扫描mapper,demo中在Dao层用@Repository 注解,这里没添加@MapperScan 也没有报错。
springboot整合druid连接池、mybatis实现多数据源动态切换的更多相关文章
- springboot整合druid数据库连接池并开启监控
简介 Druid是一个关系型数据库连接池,它是阿里巴巴的一个开源项目.Druid支持所有JDBC兼容的数据库,包括Oracle.MySQL.Derby.PostgreSQL.SQL Server.H2 ...
- springboot集成druid连接池
使用druid连接池主要有几步: 1.添加jar和依赖 <groupId>org.mybatis.spring.boot</groupId> <artifactId> ...
- Spring3.3 整合 Hibernate3、MyBatis3.2 配置多数据源/动态切换数据源 方法
一.开篇 这里整合分别采用了Hibernate和MyBatis两大持久层框架,Hibernate主要完成增删改功能和一些单一的对象查询功能,MyBatis主要负责查询功能.所以在出来数据库方言的时候基 ...
- Spring3.3 整合 Hibernate3、MyBatis3.2 配置多数据源/动态切换数据源方法
一.开篇 这里整合分别采用了Hibernate和MyBatis两大持久层框架,Hibernate主要完成增删改功能和一些单一的对象查询功能,MyBatis主要负责查询功能.所以在出来数据库方言的时候基 ...
- Spring Boot下Druid连接池+mybatis
目前Spring Boot中默认支持的连接池有dbcp,dbcp2, hikari三种连接池. 引言: 在Spring Boot下默认提供了若干种可用的连接池,Druid来自于阿里系的一个开源连 ...
- springboot使用druid连接池连接Oracle数据库的基本配置
#阿里连接池配置 #spring.datasource.druid.driver-class-name=oracle.jdbc.driver.OracleDriver #可配可不配,阿里的数据库连接池 ...
- SpringBoot下Druid连接池的使用配置
Druid是一个JDBC组件,druid 是阿里开源在 github 上面的数据库连接池,它包括三部分: * DruidDriver 代理Driver,能够提供基于Filter-Chain模式的插件体 ...
- SpringBoot 使用Druid连接池
1.pom依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId> ...
- SSM项目下Druid连接池的配置及数据源监控的使用
一,连接池的配置 在pom.xml中添加,druid的maven信息 <dependency> <groupId>com.alibaba</groupId> < ...
随机推荐
- 【错误记录】PowerShell 超级无语的语法错误(令人怀疑人生)
曾经做过测试,本文是本章优秀测试人员的精神,必须定位到原因,不然吃不下饭.其实可以很容易绕过这种问题. 环境: PowerShell 5.1.16299.64 Windows 10 现有代码如下: # ...
- 获取href连接并跳转
获取href连接: <!DOCTYPE html> <html> <head> <script src="/jquery/jquery-1.11.1 ...
- C - Reduced ID Numbers 寒假训练
T. Chur teaches various groups of students at university U. Every U-student has a unique Student Ide ...
- [CQOI2014]排序机械臂
嘟嘟嘟 最近复习复习平衡树,然后又体会到了那种感觉:"写代码半小时,debug一下午". 这题其实就是让你搞一个数据结构,支持一下操作: 1.区间翻转. 2.查询区间最小值所在位置 ...
- NPM(包管理器)作用是什么?
NPM是随同NodeJS一起安装的包管理工具,能解决NodeJS代码部署上的很多问题,常见的使用场景有以下几种: a.允许用户从NPM服务器下载别人编写的第三方包到本地使用 b.允许用户从NPM服务器 ...
- python中.py和.pyw文件的区别
:本文为博主原创文章,未经博主允许不得转载. 以下是摘录自百度问题的答案: 严格来说,它们之间的不同就只有一个:视窗运行它们的时候调用不同的执行档案. 视窗用 python.exe 运行 .py ,用 ...
- 分布式缓存技术redis系列(三)——redis高级应用(主从、事务与锁、持久化)
上文<详细讲解redis数据结构(内存模型)以及常用命令>介绍了redis的数据类型以及常用命令,本文我们来学习下redis的一些高级特性. 安全性设置 设置客户端操作秘密 redis安装 ...
- <转>大型分布式网站术语浅析
夜半睡起看书,看到一篇关于分布式网站性能优化术语的文章,个人觉得不错,分享出来... 原文地址:大型分布式网站术语分析 一.I/O优化 1.增加缓存,减少磁盘的访问次数. 2.优化磁盘的管理系统,设计 ...
- ELF格式文件分析以及运用
基于本文的一个实践<使用Python分析ELF文件优化Flash和Sram空间的案例>. 1.背景 ELF是Executable and Linkable Format缩写,其官方规范在& ...
- NOI.ac #31 MST DP、哈希
题目传送门:http://noi.ac/problem/31 一道思路好题考虑模拟$Kruskal$的加边方式,然后能够发现非最小生成树边只能在一个已经由边权更小的边连成的连通块中,而树边一定会让两个 ...