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. 解决Could not load file or assembly CefSharp.Core.dll的问题

    这个问题的中文提示是: 未能加载文件或程序集“CefSharp.Core.dll”或它的某一个依赖项.找不到指定的模块 具体原因是因为CefSharp运行时需要Visual C++ Redistrib ...

  2. EasyUI DataGrid自适应高度

    我的页面分为上下两部分,但发现下面有DataGrid的高度总是自动改,数据根本显示不出来. 后来在博客园里看到这个:http://www.cnblogs.com/xienb/archive/2013/ ...

  3. Spring集成MyBatis持久层框架

    一.MyBatis介绍 MyBatis 是一款优秀的持久层框架,它支持定制化SQL.存储过程以及高级映射.MyBatis 避免了几乎所有的JDBC代码和手动设置参数以及获取结果集,可以使用简单的XML ...

  4. python MD5加密方法

    import hashlibhash = hashlib.md5()hash.update('admin')print hash.hexdigest()

  5. php-kafka

    1.环境依赖 The extension support both PHP 5 and PHP 7. The extension requires » librdkafka >= 0.8 for ...

  6. PHP的运行机制与原理(底层)

    原文:http://www.jb51.net/article/74907.htm 说到php的运行机制还要先给大家介绍php的模块,PHP总共有三个模块:内核.Zend引擎.以及扩展层:PHP内核用来 ...

  7. strlen的容易tle情况

    for(int i=1;i<=strlen(**);i++ 这很容易tle 因为 strlen很大 int m=strlen(**)

  8. Android BaseAdapter加载多个不同的Item布局时出现UncaughtException in Thread main java.lang.ArrayIndexOutOfBoundsException: length=15; index=15

    java.lang.ArrayIndexOutOfBoundsException: length=15; index=15 异常出现的场景:在做聊天界面时,需要插入表情,图片,文字,名片,还有几种较为 ...

  9. Omi框架学习之旅 - 通过对象实例来实现组件通讯 及原理说明

    组件通讯不是讲完了吗(上帝模式还没讲哈),怎么又多了种方式啊. 你484傻,多一种选择不好吗? 其实这个不属于组件通讯啦,只是当父组件实例安装和渲染完毕后,可以执行installed这个方法(默认是空 ...

  10. go get 碰壁怎么办?

    如果要让go get顺利进行,必须注意2个问题:     1.墙:2.墙: 解决办法是安装和配置shadowsocks和polipo.shadowsocks是socks5协议,polipo是将sock ...