当前位置: 代码网 > it编程>编程语言>Java > SpringBoot实现数据库读写分离的3种方法小结

SpringBoot实现数据库读写分离的3种方法小结

2025年04月04日 Java 我要评论
一、数据库读写分离概述在大型应用系统中,随着访问量的增加,数据库常常成为系统的性能瓶颈。为了提高系统的读写性能和可用性,读写分离是一种经典的数据库架构模式。它将数据库读操作和写操作分别路由到不同的数据

一、数据库读写分离概述

在大型应用系统中,随着访问量的增加,数据库常常成为系统的性能瓶颈。为了提高系统的读写性能和可用性,读写分离是一种经典的数据库架构模式。它将数据库读操作和写操作分别路由到不同的数据库实例,通常是将写操作指向主库(master),读操作指向从库(slave)。

读写分离的主要优势:

  • 分散数据库访问压力,提高系统的整体吞吐量
  • 提升读操作的性能和并发量
  • 增强系统的可用性和容错能力

在springboot应用中,有多种方式可以实现数据库读写分离,本文将介绍三种主实现方案。

二、方案一:基于abstractroutingdatasource实现动态数据源

这种方案是基于spring提供的abstractroutingdatasource抽象类,通过重写其中的determinecurrentlookupkey()方法来实现数据源的动态切换。

2.1 实现原理

abstractroutingdatasource的核心原理是在执行数据库操作时,根据一定的策略(通常基于当前操作的上下文)动态地选择实际的数据源。通过在业务层或aop拦截器中设置上下文标识,让系统自动判断是读操作还是写操作,从而选择对应的数据源。

2.2 具体实现步骤

第一步:定义数据源枚举和上下文持有器

// 数据源类型枚举
public enum datasourcetype {
    master, // 主库,用于写操作
    slave   // 从库,用于读操作
}

// 数据源上下文持有器
public class datasourcecontextholder {
    private static final threadlocal<datasourcetype> contextholder = new threadlocal<>();
    
    public static void setdatasourcetype(datasourcetype datasourcetype) {
        contextholder.set(datasourcetype);
    }
    
    public static datasourcetype getdatasourcetype() {
        return contextholder.get() == null ? datasourcetype.master : contextholder.get();
    }
    
    public static void cleardatasourcetype() {
        contextholder.remove();
    }
}

第二步:实现动态数据源

public class dynamicdatasource extends abstractroutingdatasource {
    @override
    protected object determinecurrentlookupkey() {
        return datasourcecontextholder.getdatasourcetype();
    }
}

第三步:配置数据源

@configuration
public class datasourceconfig {
    
    @bean
    @configurationproperties(prefix = "spring.datasource.master")
    public datasource masterdatasource() {
        return datasourcebuilder.create().build();
    }
    
    @bean
    @configurationproperties(prefix = "spring.datasource.slave")
    public datasource slavedatasource() {
        return datasourcebuilder.create().build();
    }
    
    @bean
    public datasource dynamicdatasource() {
        dynamicdatasource dynamicdatasource = new dynamicdatasource();
        
        map<object, object> datasourcemap = new hashmap<>(2);
        datasourcemap.put(datasourcetype.master, masterdatasource());
        datasourcemap.put(datasourcetype.slave, slavedatasource());
        
        // 设置默认数据源为主库
        dynamicdatasource.setdefaulttargetdatasource(masterdatasource());
        dynamicdatasource.settargetdatasources(datasourcemap);
        
        return dynamicdatasource;
    }
    
    @bean
    public sqlsessionfactory sqlsessionfactory() throws exception {
        sqlsessionfactorybean sqlsessionfactorybean = new sqlsessionfactorybean();
        sqlsessionfactorybean.setdatasource(dynamicdatasource());
        
        // 设置mybatis配置
        // ...
        
        return sqlsessionfactorybean.getobject();
    }
}

第四步:实现aop拦截器,根据方法匹配规则自动切换数据源

@aspect
@component
public class datasourceaspect {
    
    // 匹配所有以select、query、get、find开头的方法为读操作
    @pointcut("execution(* com.example.service.impl.*.*(..))")
    public void servicepointcut() {}
    
    @before("servicepointcut()")
    public void switchdatasource(joinpoint point) {
        // 获取方法名
        string methodname = point.getsignature().getname();
        
        // 根据方法名判断是读操作还是写操作
        if (methodname.startswith("select") || 
            methodname.startswith("query") || 
            methodname.startswith("get") || 
            methodname.startswith("find")) {
            // 读操作使用从库
            datasourcecontextholder.setdatasourcetype(datasourcetype.slave);
        } else {
            // 写操作使用主库
            datasourcecontextholder.setdatasourcetype(datasourcetype.master);
        }
    }
    
    @after("servicepointcut()")
    public void restoredatasource() {
        // 清除数据源配置
        datasourcecontextholder.cleardatasourcetype();
    }
}

第五步:配置文件application.yml

spring:
  datasource:
    master:
      jdbc-url: jdbc:mysql://master-db:3306/test?usessl=false
      username: root
      password: root
      driver-class-name: com.mysql.cj.jdbc.driver
    slave:
      jdbc-url: jdbc:mysql://slave-db:3306/test?usessl=false
      username: root
      password: root
      driver-class-name: com.mysql.cj.jdbc.driver

第六步:使用注解方式灵活控制数据源(可选增强)

// 定义自定义注解
@target({elementtype.method, elementtype.type})
@retention(retentionpolicy.runtime)
@documented
public @interface datasource {
    datasourcetype value() default datasourcetype.master;
}

// 修改aop拦截器,优先使用注解指定的数据源
@aspect
@component
public class datasourceaspect {
    
    @pointcut("@annotation(com.example.annotation.datasource)")
    public void datasourcepointcut() {}
    
    @before("datasourcepointcut()")
    public void switchdatasource(joinpoint point) {
        methodsignature signature = (methodsignature) point.getsignature();
        method method = signature.getmethod();
        
        datasource datasource = method.getannotation(datasource.class);
        if (datasource != null) {
            datasourcecontextholder.setdatasourcetype(datasource.value());
        }
    }
    
    @after("datasourcepointcut()")
    public void restoredatasource() {
        datasourcecontextholder.cleardatasourcetype();
    }
}

// 在service方法上使用
@service
public class userserviceimpl implements userservice {
    
    @override
    @datasource(datasourcetype.slave)
    public list<user> findallusers() {
        return usermapper.selectall();
    }
    
    @override
    @datasource(datasourcetype.master)
    public void createuser(user user) {
        usermapper.insert(user);
    }
}

2.3 优缺点分析

优点:

  • 实现简单,不依赖第三方组件
  • 侵入性小,对业务代码影响较小
  • 灵活性高,可以根据业务需求灵活切换数据源
  • 支持多数据源扩展,不限于主从两个库

缺点:

  • 需要手动指定或通过约定规则判断读写操作

适用场景:

  • 中小型项目,读写请求分离明确
  • 对中间件依赖要求低的场景
  • 临时性能优化,快速实现读写分离

三、方案二:基于shardingsphere-jdbc实现读写分离

shardingsphere-jdbc是apache shardingsphere项目下的一个子项目,它通过客户端分片的方式,为应用提供了透明化的读写分离和分库分表等功能。

3.1 实现原理

shardingsphere-jdbc通过拦截jdbc驱动,重写sql解析与执行流程来实现读写分离。它能够根据sql语义自动判断读写操作,并将读操作负载均衡地分发到多个从库。

3.2 具体实现步骤

第一步:添加依赖

<dependency>
    <groupid>org.apache.shardingsphere</groupid>
    <artifactid>shardingsphere-jdbc-core-spring-boot-starter</artifactid>
    <version>5.2.1</version>
</dependency>
<dependency>
    <groupid>com.mysql</groupid>
    <artifactid>mysql-connector-j</artifactid>
    <scope>runtime</scope>
</dependency>

第二步:配置文件application.yml

spring:
  shardingsphere:
    mode:
      type: memory
    datasource:
      names: master,slave1,slave2
      master:
        type: com.zaxxer.hikari.hikaridatasource
        driver-class-name: com.mysql.cj.jdbc.driver
        jdbc-url: jdbc:mysql://master-db:3306/test?usessl=false
        username: root
        password: root
      slave1:
        type: com.zaxxer.hikari.hikaridatasource
        driver-class-name: com.mysql.cj.jdbc.driver
        jdbc-url: jdbc:mysql://slave1-db:3306/test?usessl=false
        username: root
        password: root
      slave2:
        type: com.zaxxer.hikari.hikaridatasource
        driver-class-name: com.mysql.cj.jdbc.driver
        jdbc-url: jdbc:mysql://slave2-db:3306/test?usessl=false
        username: root
        password: root
    rules:
      readwrite-splitting:
        data-sources:
          readwrite_ds:
            type: static
            props:
              write-data-source-name: master
              read-data-source-names: slave1,slave2
            load-balancer-name: round_robin
        load-balancers:
          round_robin:
            type: round_robin
    props:
      sql-show: true # 开启sql显示,方便调试

第三步:创建数据源配置类

@configuration
public class datasourceconfig {
    
    // 无需额外配置,shardingsphere-jdbc会自动创建并注册datasource
    
    @bean
    @configurationproperties(prefix = "mybatis")
    public sqlsessionfactorybean sqlsessionfactorybean(datasource datasource) {
        sqlsessionfactorybean sqlsessionfactorybean = new sqlsessionfactorybean();
        sqlsessionfactorybean.setdatasource(datasource);
        return sqlsessionfactorybean;
    }
}

第四步:强制主库查询的注解(可选)

在某些场景下,即使是查询操作也需要从主库读取最新数据,shardingsphere提供了hint机制来实现这一需求。

// 定义主库查询注解
@target({elementtype.method})
@retention(retentionpolicy.runtime)
@documented
public @interface masterroute {
}

// 创建aop切面拦截器
@aspect
@component
public class masterrouteaspect {
    
    @around("@annotation(com.example.annotation.masterroute)")
    public object aroundmasterroute(proceedingjoinpoint joinpoint) throws throwable {
        try {
            hintmanager.getinstance().setwriterouteonly();
            return joinpoint.proceed();
        } finally {
            hintmanager.clear();
        }
    }
}

// 在需要主库查询的方法上使用注解
@service
public class orderserviceimpl implements orderservice {
    
    @autowired
    private ordermapper ordermapper;
    
    @override
    @masterroute
    public order getlatestorder(long userid) {
        // 这里的查询会路由到主库
        return ordermapper.findlatestbyuserid(userid);
    }
}

3.3 优缺点分析

优点:

  • 自动识别sql类型,无需手动指定读写数据源
  • 支持多从库负载均衡
  • 提供丰富的负载均衡算法(轮询、随机、权重等)
  • 完整的分库分表能力,可无缝扩展
  • 对应用透明,业务代码无需修改

缺点:

  • 引入额外的依赖和学习成本
  • 配置相对复杂
  • 性能有轻微损耗(sql解析和路由)

适用场景:

  • 中大型项目,有明确的读写分离需求
  • 需要负载均衡到多从库的场景
  • 未来可能需要分库分表的系统

四、方案三:基于mybatis插件实现读写分离

mybatis提供了强大的插件机制,允许在sql执行的不同阶段进行拦截和处理。通过自定义插件,可以实现基于sql解析的读写分离功能。

4.1 实现原理

mybatis允许拦截执行器的queryupdate方法,通过拦截这些方法,可以在sql执行前动态切换数据源。这种方式的核心是编写一个拦截器,分析即将执行的sql语句类型(select/insert/update/delete),然后根据sql类型切换到相应的数据源。

4.2 具体实现步骤

第一步:定义数据源和上下文(与方案一类似)

public enum datasourcetype {
    master, slave
}

public class datasourcecontextholder {
    private static final threadlocal<datasourcetype> contextholder = new threadlocal<>();
    
    public static void setdatasourcetype(datasourcetype datasourcetype) {
        contextholder.set(datasourcetype);
    }
    
    public static datasourcetype getdatasourcetype() {
        return contextholder.get() == null ? datasourcetype.master : contextholder.get();
    }
    
    public static void cleardatasourcetype() {
        contextholder.remove();
    }
}

public class dynamicdatasource extends abstractroutingdatasource {
    @override
    protected object determinecurrentlookupkey() {
        return datasourcecontextholder.getdatasourcetype();
    }
}

第二步:实现mybatis拦截器

@intercepts({
    @signature(type = executor.class, method = "query", args = {mappedstatement.class, object.class, rowbounds.class, resulthandler.class}),
    @signature(type = executor.class, method = "query", args = {mappedstatement.class, object.class, rowbounds.class, resulthandler.class, cachekey.class, boundsql.class}),
    @signature(type = executor.class, method = "update", args = {mappedstatement.class, object.class})
})
@component
public class readwritesplittinginterceptor implements interceptor {
    
    @override
    public object intercept(invocation invocation) throws throwable {
        object[] args = invocation.getargs();
        mappedstatement ms = (mappedstatement) args[0];
        
        try {
            // 判断是否为事务
            boolean istransactional = transactionsynchronizationmanager.isactualtransactionactive();
            
            // 如果是事务,则使用主库
            if (istransactional) {
                datasourcecontextholder.setdatasourcetype(datasourcetype.master);
                return invocation.proceed();
            }
            
            // 根据sql类型选择数据源
            if (ms.getsqlcommandtype() == sqlcommandtype.select) {
                // 读操作使用从库
                datasourcecontextholder.setdatasourcetype(datasourcetype.slave);
            } else {
                // 写操作使用主库
                datasourcecontextholder.setdatasourcetype(datasourcetype.master);
            }
            
            return invocation.proceed();
        } finally {
            // 清除数据源配置
            datasourcecontextholder.cleardatasourcetype();
        }
    }
    
    @override
    public object plugin(object target) {
        if (target instanceof executor) {
            return plugin.wrap(target, this);
        }
        return target;
    }
    
    @override
    public void setproperties(properties properties) {
        // 可以从配置文件加载属性
    }
}

第三步:配置数据源和mybatis插件

@configuration
public class datasourceconfig {
    
    @bean
    @configurationproperties(prefix = "spring.datasource.master")
    public datasource masterdatasource() {
        return datasourcebuilder.create().build();
    }
    
    @bean
    @configurationproperties(prefix = "spring.datasource.slave")
    public datasource slavedatasource() {
        return datasourcebuilder.create().build();
    }
    
    @bean
    public datasource dynamicdatasource() {
        dynamicdatasource dynamicdatasource = new dynamicdatasource();
        
        map<object, object> datasourcemap = new hashmap<>(2);
        datasourcemap.put(datasourcetype.master, masterdatasource());
        datasourcemap.put(datasourcetype.slave, slavedatasource());
        
        dynamicdatasource.setdefaulttargetdatasource(masterdatasource());
        dynamicdatasource.settargetdatasources(datasourcemap);
        
        return dynamicdatasource;
    }
    
    @bean
    public sqlsessionfactory sqlsessionfactory(@autowired readwritesplittinginterceptor interceptor) throws exception {
        sqlsessionfactorybean sqlsessionfactorybean = new sqlsessionfactorybean();
        sqlsessionfactorybean.setdatasource(dynamicdatasource());
        
        // 添加mybatis插件
        sqlsessionfactorybean.setplugins(new interceptor[]{interceptor});
        
        // 其他mybatis配置
        // ...
        
        return sqlsessionfactorybean.getobject();
    }
}

第四步:强制主库查询注解(可选)

@configuration
public class datasourceconfig {
    
    @bean
    @configurationproperties(prefix = "spring.datasource.master")
    public datasource masterdatasource() {
        return datasourcebuilder.create().build();
    }
    
    @bean
    @configurationproperties(prefix = "spring.datasource.slave")
    public datasource slavedatasource() {
        return datasourcebuilder.create().build();
    }
    
    @bean
    public datasource dynamicdatasource() {
        dynamicdatasource dynamicdatasource = new dynamicdatasource();
        
        map<object, object> datasourcemap = new hashmap<>(2);
        datasourcemap.put(datasourcetype.master, masterdatasource());
        datasourcemap.put(datasourcetype.slave, slavedatasource());
        
        dynamicdatasource.setdefaulttargetdatasource(masterdatasource());
        dynamicdatasource.settargetdatasources(datasourcemap);
        
        return dynamicdatasource;
    }
    
    @bean
    public sqlsessionfactory sqlsessionfactory(@autowired readwritesplittinginterceptor interceptor) throws exception {
        sqlsessionfactorybean sqlsessionfactorybean = new sqlsessionfactorybean();
        sqlsessionfactorybean.setdatasource(dynamicdatasource());
        
        // 添加mybatis插件
        sqlsessionfactorybean.setplugins(new interceptor[]{interceptor});
        
        // 其他mybatis配置
        // ...
        
        return sqlsessionfactorybean.getobject();
    }
}

4.3 优缺点分析

优点:

  • 自动识别sql类型,无需手动指定数据源
  • 可灵活扩展,支持复杂的路由规则
  • 基于mybatis原生插件机制,无需引入额外的中间件

缺点:

  • 仅适用于使用mybatis的项目
  • 需要理解mybatis插件机制
  • 没有内置的负载均衡能力,需要额外开发
  • 可能与其他mybatis插件产生冲突
  • 事务管理较为复杂

适用场景:

  • 纯mybatis项目
  • 定制化需求较多的场景
  • 对第三方中间件有限制的项目
  • 需要对读写分离有更精细控制的场景

五、三种方案对比与选型指南

5.1 功能对比

功能特性方案一:abstractroutingdatasource方案二:shardingsphere-jdbc方案三:mybatis插件
自动识别sql类型❌ 需要手动或通过规则指定✅ 自动识别✅ 自动识别
多从库负载均衡❌ 需要自行实现✅ 内置多种算法❌ 需要自行实现
与分库分表集成❌ 不支持✅ 原生支持❌ 需要额外开发
开发复杂度⭐⭐ 中等⭐ 较低⭐⭐⭐ 较高
配置复杂度⭐ 较低⭐⭐⭐ 较高⭐⭐ 中等

5.2 选型建议

选择方案一(abstractroutingdatasource)的情况:

  • 项目规模较小,读写分离规则简单明确
  • 对第三方依赖敏感,希望减少依赖
  • 团队对spring原生机制较为熟悉
  • 系统处于早期阶段,可能频繁变动

选择方案二(shardingsphere-jdbc)的情况:

  • 中大型项目,有复杂的数据库访问需求
  • 需要多从库负载均衡能力
  • 未来可能需要分库分表
  • 希望尽量减少代码侵入
  • 对开发效率要求较高

选择方案三(mybatis插件)的情况:

  • 项目完全基于mybatis架构
  • 团队对mybatis插件机制较为熟悉
  • 有特定的定制化需求
  • 希望对sql路由有更细粒度的控制
  • 对框架依赖有严格限制

六、实施读写分离的最佳实践

6.1 数据一致性处理

从库数据同步存在延迟,这可能导致读取到过期数据的问题。处理方法:

  • 提供强制主库查询的选项:对于需要最新数据的查询,提供从主库读取的机制
  • 会话一致性:同一会话内的读写操作使用相同的数据源
  • 延迟检测:定期检测主从同步延迟,当延迟超过阈值时暂停从库查询
// 实现延迟检测的示例
@component
@slf4j
public class replicationlagmonitor {
    
    @autowired
    private jdbctemplate masterjdbctemplate;
    
    @autowired
    private jdbctemplate slavejdbctemplate;
    
    private atomicboolean slavetoolagged = new atomicboolean(false);
    
    @scheduled(fixedrate = 5000) // 每5秒检查一次
    public void checkreplicationlag() {
        try {
            // 在主库写入标记
            string mark = uuid.randomuuid().tostring();
            masterjdbctemplate.update("insert into replication_marker(marker, create_time) values(?, now())", mark);
            
            // 等待一定时间,给从库同步的机会
            thread.sleep(1000);
            
            // 从从库查询该标记
            integer count = slavejdbctemplate.queryforobject(
                "select count(*) from replication_marker where marker = ?", integer.class, mark);
            
            // 判断同步延迟
            boolean lagged = (count == null || count == 0);
            slavetoolagged.set(lagged);
 
            if (lagged) {
                log.warn("slave replication lag detected, routing read operations to master");
            } else {
                log.info("slave replication is in sync");
            }
        } catch (exception e) {
            log.error("failed to check replication lag", e);
            slavetoolagged.set(true); // 发生异常时,保守地认为从库延迟过大
        } finally{
            // 删除标记数据
            masterjdbctemplate.update("delete from replication_marker where marker = ?", mark);
        }
    }
    
    public boolean isslavetoolagged() {
        return slavetoolagged.get();
    }
}

6.2 事务管理

读写分离环境下的事务处理需要特别注意:

  • 事务内操作都走主库:确保事务一致性
  • 避免长事务:长事务会长时间锁定主库资源
  • 区分只读事务:对于只读事务,可以考虑路由到从库

6.4 监控与性能优化

  • 监控读写比例:了解系统的读写比例,优化资源分配
  • 慢查询监控:监控各数据源的慢查询
  • 连接池优化:根据实际负载调整连接池参数
# hikaricp连接池配置示例
spring:
  datasource:
    master:
      # 主库偏向写操作,连接池可以适当小一些
      maximum-pool-size: 20
      minimum-idle: 5
    slave:
      # 从库偏向读操作,连接池可以适当大一些
      maximum-pool-size: 50
      minimum-idle: 10

七、总结

在实施读写分离时,需要特别注意数据一致性、事务管理和故障处理等方面的问题。

通过合理的架构设计和细致的实现,读写分离可以有效提升系统的读写性能和可扩展性,为应用系统的高可用和高性能提供有力支持。

无论选择哪种方案,请记住读写分离是一种架构模式,而非解决所有性能问题的万能药。在实施前应充分评估系统的实际需求和潜在风险,确保收益大于成本。

到此这篇关于springboot实现数据库读写分离的3种方法小结的文章就介绍到这了,更多相关springboot数据库读写分离内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com