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 也没有报错。

demo下载(CSDN)

gitbub源码下载

springboot整合druid连接池、mybatis实现多数据源动态切换的更多相关文章

  1. springboot整合druid数据库连接池并开启监控

    简介 Druid是一个关系型数据库连接池,它是阿里巴巴的一个开源项目.Druid支持所有JDBC兼容的数据库,包括Oracle.MySQL.Derby.PostgreSQL.SQL Server.H2 ...

  2. springboot集成druid连接池

    使用druid连接池主要有几步: 1.添加jar和依赖 <groupId>org.mybatis.spring.boot</groupId> <artifactId> ...

  3. Spring3.3 整合 Hibernate3、MyBatis3.2 配置多数据源/动态切换数据源 方法

    一.开篇 这里整合分别采用了Hibernate和MyBatis两大持久层框架,Hibernate主要完成增删改功能和一些单一的对象查询功能,MyBatis主要负责查询功能.所以在出来数据库方言的时候基 ...

  4. Spring3.3 整合 Hibernate3、MyBatis3.2 配置多数据源/动态切换数据源方法

    一.开篇 这里整合分别采用了Hibernate和MyBatis两大持久层框架,Hibernate主要完成增删改功能和一些单一的对象查询功能,MyBatis主要负责查询功能.所以在出来数据库方言的时候基 ...

  5. Spring Boot下Druid连接池+mybatis

      目前Spring Boot中默认支持的连接池有dbcp,dbcp2, hikari三种连接池.  引言: 在Spring Boot下默认提供了若干种可用的连接池,Druid来自于阿里系的一个开源连 ...

  6. springboot使用druid连接池连接Oracle数据库的基本配置

    #阿里连接池配置 #spring.datasource.druid.driver-class-name=oracle.jdbc.driver.OracleDriver #可配可不配,阿里的数据库连接池 ...

  7. SpringBoot下Druid连接池的使用配置

    Druid是一个JDBC组件,druid 是阿里开源在 github 上面的数据库连接池,它包括三部分: * DruidDriver 代理Driver,能够提供基于Filter-Chain模式的插件体 ...

  8. SpringBoot 使用Druid连接池

    1.pom依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId> ...

  9. SSM项目下Druid连接池的配置及数据源监控的使用

    一,连接池的配置 在pom.xml中添加,druid的maven信息 <dependency> <groupId>com.alibaba</groupId> < ...

随机推荐

  1. ccf题库中2015年12月2号消除类游戏

    题目如下: 问题描述 消除类游戏是深受大众欢迎的一种游戏,游戏在一个包含有n行m列的游戏棋盘上进行,棋盘的每一行每一列的方格上放着一个有颜色的棋子,当一行或一列上有连续三个或更多的相同颜色的棋子时,这 ...

  2. January 31st, 2018 Week 05th Wednesday

    Real love is not just instinct, but intent. 真正的爱不是身体上的一见钟情,而是要用心去经营. What is real love? Honestly, I ...

  3. 个人技术博客Alpha----Android Studio学习

    项目联系: 本次项目我主要负责Android studio的后端,以及游戏文案游戏策划,结果后来事情太散了,Android studio学的不咋地,文案写完还有帮着写一写数据库的插入语句,然后就是跟队 ...

  4. Department and Student

    软工结对作业之二 本人ID:杨光海天 031502634 队友(大佬)ID:陈涵 031502106 GitHub链接 BIN文件地址 代码文件 整体概况 模型建立 学生类,属性包括: * 1)编号 ...

  5. 在Eclipse中使用Maven jetty的debug模式

    1.右键项目debug as添加mvn命令: jetty:run 2.进入eclipse的菜单Run->Debug configurations,会看到maven build下对应的项目的mvn ...

  6. [MySQL学习]STRICT_ALL_TABLES相应的OUT of RANGE VALUE FOR COLUMN和DATA truncated FOR COLUMN

    版权声明:声明:本文档能够转载,须署名原作者. 作者:无为 qq:490073687 周祥兴 zhou.xiangxing210@163.com https://blog.csdn.net/Rooki ...

  7. Domain Adaptation (1)选题讲解

    1 所选论文 论文题目: <Unsupervised Domain Adaptation with Residual Transfer Networks> 论文信息: NIPS2016, ...

  8. PAT A1151 LCA in a Binary Tree (30 分)——二叉树,最小公共祖先(lca)

    The lowest common ancestor (LCA) of two nodes U and V in a tree is the deepest node that has both U ...

  9. ubuntu开机自动运行用Qt写的程序

    这里介绍一种在ubuntu系统开机自动运行使用Qt编写的程序的方法.首先要注意要自动运行Qt编的程序,不需要先打开Qt,而是直接运行编译好的与工程名同名的可执行文件即可,比如我要运行的工程为QRDec ...

  10. 解决linux下无线网卡被物理禁用问题

    困扰了我好几天终于解决了这个问题,这里写出来,给再遇到这样问题的朋友做个借鉴! 笔记本:lenovo 问题描述:wifi无线网卡开关是打开的,但是安装linux(fedora \ ubuntu )后, ...