本文来自网易云社区

作者:王超

应用场景:项目中有一些报表统计与查询功能,对数据实时性要求不高,因此考虑对报表的统计与查询去操作slave db,减少对master的压力。

根据网上多份资料测试发现总是使用master数据源,无法切换到slave,经过多次调试修改现已完美通过,现整理下详细步骤和完整代码如下:

实现方式:配置多个数据源,使用Spring AOP实现拦截注解实现数据源的动态切换。

1. application.yml数据库配置:druid:

  type: com.alibaba.druid.pool.DruidDataSource
  master:
    url: jdbc:mysql://127.0.0.1:3306/test?characterEncoding=UTF-8&autoReconnect=true&zeroDateTimeBehavior=convertToNull&useUnicode=true
    driver-class-name: com.mysql.jdbc.Driver
    username: test
    password: 123
    initial-size: 5
    max-active: 10
    min-idle: 5
    max-wait: 60000
    time-between-eviction-runs-millis: 3000
    min-evictable-idle-time-millis: 300000
    validation-query: SELECT 'x' FROM DUAL
    test-while-idle: true
    test-on-borrow: true
    test-on-return: false
    filters: stat,wall,log4j2
  slave:
    url: jdbc:mysql://127.0.0.1:3307/test?characterEncoding=UTF-8&autoReconnect=true&zeroDateTimeBehavior=convertToNull&useUnicode=true
    driver-class-name: com.mysql.jdbc.Driver
    username: test
    password: 123
    initial-size: 5
    max-active: 10
    min-idle: 5
    max-wait: 60000
    time-between-eviction-runs-millis: 3000
    min-evictable-idle-time-millis: 300000
    validation-query: SELECT 'x' FROM DUAL
    test-while-idle: true
    test-on-borrow: true
    test-on-return: false
    filters: stat,wall,log4j2

2. 通过MybatisAutoConfiguration实现多数据源注入:

@Configuration
@EnableTransactionManagement
public class DataSourceConfiguration extends MybatisAutoConfiguration {     @Value("${druid.type}")
    private Class<? extends DataSource> dataSourceType;     @Bean(name = "masterDataSource")
    @Primary
    @ConfigurationProperties(prefix = "druid.master")
    public DataSource masterDataSource(){
        return DataSourceBuilder.create().type(dataSourceType).build();
    }     @Bean(name = "slaveDataSource")
    @ConfigurationProperties(prefix = "druid.slave")
    public DataSource slaveDataSource(){
        return DataSourceBuilder.create().type(dataSourceType).build();
    }     @Bean
    @Override
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
        return super.sqlSessionFactory(dataSource());
    }     @Bean(name = "dataSource")
    public AbstractRoutingDataSource dataSource() {
        MasterSlaveRoutingDataSource proxy = new MasterSlaveRoutingDataSource();
        Map<Object, Object> targetDataResources = new HashMap<>();
        targetDataResources.put(DbContextHolder.DbType.MASTER, masterDataSource());
        targetDataResources.put(DbContextHolder.DbType.SLAVE, slaveDataSource());
        proxy.setDefaultTargetDataSource(masterDataSource());
        proxy.setTargetDataSources(targetDataResources);
        proxy.afterPropertiesSet();
        return proxy;
    }
}

3. 基于 AbstractRoutingDataSource 和 AOP 的多数据源的配置

我们自己定义一个DataSource类,来继承 AbstractRoutingDataSource:
public class MasterSlaveRoutingDataSource extends AbstractRoutingDataSource {
    @Override
    protected Object determineCurrentLookupKey() {
        return DbContextHolder.getDbType();
    }
}这里通过determineCurrentLookupKey()返回的不同key到sqlSessionFactory中获取对应数据源然后使用ThreadLocal来存放线程的变量,将不同的数据源标识记录在ThreadLocal中
public class DbContextHolder {
    public enum DbType{
        MASTER, SLAVE
    }
    private static final ThreadLocal<DbType> contextHolder = new ThreadLocal<>();
    public static void setDbType(DbType dbType){
        if (dbType==null) {
            throw new NullPointerException();
        }
        contextHolder.set(dbType);
    }
    public static DbType getDbType(){
        return contextHolder.get()==null?DbType.MASTER:contextHolder.get();
    }
    public static void clearDbType(){
        contextHolder.remove();
    }
}

4. 注解实现

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ReadOnlyConnection {
}@Aspect
@Component
public class ReadOnlyConnectionInterceptor implements Ordered {
    @Around("@annotation(readOnlyConnection)")
    public Object proceed(ProceedingJoinPoint proceedingJoinPoint, ReadOnlyConnection readOnlyConnection) throws Throwable {
        try {
            DbContextHolder.setDbType(DbContextHolder.DbType.SLAVE);
            Object result = proceedingJoinPoint.proceed();
            return result;
        }finally {
            DbContextHolder.clearDbType();
        }
    }
    @Override
    public int getOrder() {
        return 0;
    }
}

5. 应用方式:

service层接口增加ReadOnlyConnection注解即可:
@ReadOnlyConnectionpublic CommonPagingVO<GroupGoodsVO> 
pagingByCondition(GroupGoodsCondition condition, int pageNum, int pageSize)
 {  
 Page<GroupGoodsVO> 
 page = PageHelper.startPage(pageNum, pageSize).doSelectPage(() 
 -> groupGoodsMapper.listByCondition(condition));   
 return CommonPagingVO.get(page,page.getResult());
 }
对于未加ReadOnlyConnection注解的默认使用masterDataSource。

网易云免费体验馆,0成本体验20+款云产品!

更多网易研发、产品、运营经验分享请访问网易云社区

相关文章:
【推荐】 Foxman,基于微核架构的Mock解决方案

Spring Boot + Mybatis 多数据源配置实现读写分离的更多相关文章

  1. spring boot mybatis 多数据源配置

    package com.xynet.statistics.config.dataresources; import org.springframework.jdbc.datasource.lookup ...

  2. spring boot Mybatis多数据源配置

    关于 有时候,随着业务的发展,项目关联的数据来源会变得越来越复杂,使用的数据库会比较分散,这个时候就会采用多数据源的方式来获取数据.另外,多数据源也有其他好处,例如分布式数据库的读写分离,集成多种数据 ...

  3. spring boot mybatis多多数据源解决方法

    在我们的项目中不免会遇到需要在一个项目中使用多个数据源的问题,像我在得到一个任务将用户的聊天记录进行迁移的时候,就是用到了三个数据源,当时使用的AOP的编程方式根据访问的方法的不同进行动态的切换数据源 ...

  4. spring boot +mybatis(通过properties配置) 集成

    注:日常学习记录贴,下面描述的有误解的话请指出,大家一同学习. 因为我公司现在用的是postgresql数据库,所以我也用postgresql进行测试 一.前言 1.Spring boot 会默认读取 ...

  5. Spring MVC+Mybatis 多数据源配置

    文章来自:https://www.jianshu.com/p/fddcc1a6b2d8 1. 继承AbstractRoutingDataSource AbstractRoutingDataSource ...

  6. spring boot sharding-jdbc实现分佈式读写分离和分库分表的实现

    分布式读写分离和分库分表采用sharding-jdbc实现. sharding-jdbc是当当网推出的一款读写分离实现插件,其他的还有mycat,或者纯粹的Aop代码控制实现. 接下面用spring ...

  7. spring boot jpa 多数据源配置

    在实际项目中往往会使用2个数据源,这个时候就需要做额外的配置了.下面的配置在2.0.1.RELEASE 测试通过 1.配置文件 配置两个数据源 spring.datasource.url=jdbc:m ...

  8. spring boot + mybatis + druid配置实践

    最近开始搭建spring boot工程,将自身实践分享出来,本文将讲述spring boot + mybatis + druid的配置方案. pom.xml需要引入mybatis 启动依赖: < ...

  9. spring boot(四) 多数据源

    前言 前一篇中我们使用spring boot+mybatis创建了单一数据源,其中单一数据源不需要我们自己手动创建,spring boot自动配置在程序启动时会替我们创建好数据源. 准备工作 appl ...

随机推荐

  1. Date 对象 时间格式注意事项

    Date 对象,是操作日期和时间的对象. Date 为内置的构造函数, 通过 new Date () 来获取当前本地日期与时间 const time = new Date console.log(ti ...

  2. ecshop分类页把分类描述改成FCKeditor编辑器

    最近放一个网站 http://www.macklin.cn/productline/35 有个产品分类页面需要添加分类缩略图和图文的描述 一.首先说下添加分类缩略图的步骤吧 1,依葫芦画瓢,参照的是e ...

  3. Kendo UI 特效概述

    Kendo UI 特效概述 Kendo UI Fx 提供了一个丰富,可扩展,性能经过优化的工具集合用来完成 HTML 元素的过渡显示.每种特效近可能的使用 CSS Transition ,对于一些老版 ...

  4. JavaWeb_05_xml相关&dtd快速入门

    学东西怎么学,是什么,能做什么,怎么去做!! 1.xml的简介 1.eXtensible Markup Language:可扩展标记型语言 标记型语言:html是标记型语言 也是使用标签来操作 可扩展 ...

  5. PHP实现正态分布的累积概率函数

    在实际项目中,遇到需要正态分布算法去计算一个数值在整体的分布区间,例如:  100,90,80,70,60,50,40,30,20,10共10个数,按从高到低的顺序排序,总数的10%分布区域为极高频, ...

  6. GetRelativePath获取相对路径

    public static string GetRelativePath(string baseDirPath, string subFullPath) { // ForceBasePath to a ...

  7. 晒一下MAC下终端颜色配置

    效果图: ~/.vimrc 配置 filetype on set history=1000 set background=dark syntax on set autoindent set smart ...

  8. Python——三目运算符

    一.三目运算符 1.if语句三目运算符语法格式 Python可以通过if'语句来实现三目运算符的功能,因此可以把这种if语句当做三目运算符,具体语法格式如下: 返回True执行 if 表达式 else ...

  9. Mybatis学习记录(1)

    1.Mybatis介绍     Mybatis是apache的一个开源项目iBatis,Mybatis是一个优秀的持久层框架,他对jdbc的操作数据库的过程进行封装,使开发者只需要关注sql本身,不需 ...

  10. C# 获取Google Chrome的书签

    其实这个很简单,就是读取一个在用户目录里面的一个Bookmarks文件就好了. 先建立几个实体类 public class GoogleChrome_bookMark_meta_info { publ ...