本文来自网易云社区

作者:王超

应用场景:项目中有一些报表统计与查询功能,对数据实时性要求不高,因此考虑对报表的统计与查询去操作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. 读取jar包内的文件内容

    package com.chanpion.boot; import org.springframework.util.ResourceUtils; import java.io.File; impor ...

  2. linux-2.6.22.6/Makefile:416: *** mixed implicit and normal rules: deprecated syntax

    今天在按照韦东山大哥的教程流程编译内核的时候出现了这个问题      linux-2.6.22.6/Makefile:416: *** mixed implicit and normal rules: ...

  3. 对于拼接进去的html原来绑定的jq事件失效

    JQ拼接显示的页面中鼠标事件失效 由于是先加载html在用js层绑定的所有后来加进来的html内容就不再绑定js了 所以我们需要利用delegate绑定,但是同样道理也不能写在普通的方法层里,因为这样 ...

  4. 零基础逆向工程18_PE结构02_联合体_节表_PE加载过程

    联合体 特点 1.联合体的成员是共享内存空间的 2.联合体的内存空间大小是联合体成员中对内存空间大小要求最大的空间大小 3.联合体最多只有一个成员有效 节表数据结构说明 PE 加载 过程 FileBu ...

  5. Godaddy虚拟主机新建mysql数据库 2019最新

    第一次用狗爹,完全摸不着路子. 网站本地已搭建,不知道数据库是在哪里上传. 百度搜索结果都是四五年前的旧内容,耽误时间. 还是问客服,Godaddy的客服确实不赖 godaddy虚拟主机如何新建数据库 ...

  6. ios 身份证照片识别信息

    一个近乎完整的可识别中国身份证信息的Demo就问问你霸气不

  7. 突然心血来潮,想写写我在java面试中遇到的事。作为一个应届生,我觉得我的情况都与大部分应届生是差不多的,希望你们能在这上面得到一些有用的

    面试过程吧,怎么说呢?从一开始接触面试到现在成功了几家,这中间我确实收获了许多,那我就从我第一次面试开始讲吧. 第一次面试是有人介绍过来的,总之还是有一位贵人相助,所以第一次面试时,面试官很好没有怎么 ...

  8. CF Gym 100187B A Lot of Joy (古典概型)

    题意:给两个一样的只含有26个小写字母的字符串,然后两个分别做一下排列,问如果对应位置的字母相等那么就愉悦值就加一,问愉悦值的期望是多少? 题解:只考虑两个序列相对的位置,那么就相当于固定一个位置,另 ...

  9. 使用Selennium实现短信轰炸机

    前言 可以用来轰炸一下骗子,但最好不要乱用.本来初学Python,仅当学习. selenium和ChromeDriver的安装与配置 可参考这篇博客,这里不再赘述. 程序实现 短信轰炸机的原理是利用一 ...

  10. Maven settings.xml配置详解

    首先:Maven中央仓库的搜索全部公共jar包的地址是,http://search.maven.org/ ===Maven基础-默认中央仓库============================== ...