本文来自网易云社区

作者:王超

应用场景:项目中有一些报表统计与查询功能,对数据实时性要求不高,因此考虑对报表的统计与查询去操作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. is 和 == 区别 编码的问题 id()函数

    一丶is 和 == 的区别 == 比较的是值 is 比较的是内存地址 #字符串 a = "abc" b = "abc" print(a == b) print( ...

  2. Kendo UI 初始化 Data 属性

    初始化 Data 属性 前面在介绍准备 Kendo UI 开发环境时我们使用 jQuery 的方法将一个  HTML 元素转换成一个 Kendo UI 控制项: $(“#datepicker”).ke ...

  3. 2、HTTP状态码

    HTTP状态码 当浏览者访问一个网页时,浏览者的浏览器会向网页所在服务器发出请求.当浏览器接收并显示网页前,此网页所在的服务器会返回一个包含HTTP状态码的信息头(server header)用以响应 ...

  4. SPEC CPU 2006编译perl 出错:undefined reference to `pow'

    问题来源: 编译spec2006时,出现如下错误: cc -L/home/yrtan/benchmark/2006/CPU2006v1.0.1/tools/output/lib -L/usr/loca ...

  5. 利用bintray-release插件上传到Bintray- HTTP/1.1 404 Not Found [message:Repo 'maven' was not found]问题解决

    凡是网上教程 有个5678步的总有这样或者那样的坑. 上周撸了一个小工具准备上传到jcenter,方便管理以及以后使用.看了一下教程,短短几步,弄了很久. 按Hongyang的教程http://www ...

  6. zabbix2升级zabbix3

    1.停服zabbix2,停服数据库/etc/init.d/zabbix_server stop/etc/init.d/mysqld stop 2.物理备份数据库cd /var/lib/mysql/ta ...

  7. C++拾遗(五)——类

    类是 C++ 中最重要的特征.C++ 语言的早期版本被命名为“带类的 C(Cwith Classes)”,以强调类机制的中心作用.随着语言的演变,创建类的配套支持也在不断增加.语言设计的主要目标也变成 ...

  8. Exchange DSAccess 事件分析

    本文介绍了如何使用事件 ID 2080 来帮助诊断 Exchange DSAccess 问题中所包含的信息. 许多朋友经常遇到Active Directory 域和Exchange 服务器通信问题.那 ...

  9. JMeter配置元件作用域

  10. 在广州学习PHP零基础可以学习吗?

    PHP现今作为互联网运用很广泛的编程语言,市场需求量也越来越高,而PHP开发工程师的薪资也是一路水涨船高,更多的人看到了PHP的发展前景,纷纷都想投入到PHP的开发大军中来,那么对于很多转行或者零基础 ...