商道如狼道 发表于 2025-2-15 01:24:10

九.Spring Boot使用 ShardingSphere + MyBatis + Druid 举行分库分表

前言

在当代化微服务架构中,随着数据量的不断增长,单一数据库已难以满足高可用性、扩展性和性能要求。ShardingSphere 提供了分库分表的能力,资助我们轻松实现水平拆分。本文将介绍怎样在 Spring Boot 项目中,结合 MyBatis 和 Druid,实现分库分表的功能。
提示:以下是本篇文章正文内容,下面案例可供参考
一、引入依赖

在父项目中引入shardingsphere-jdbc依赖
dependencies {
       ...
       implementation 'com.alibaba:druid-spring-boot-3-starter:1.2.24'
   implementation 'com.mysql:mysql-connector-j:9.2.0'
   implementation 'org.apache.shardingsphere:shardingsphere-jdbc:5.5.2'
}
二、创建一个light-db_1备用数据库

创建一个light-db_1作为分库,表结构和light-db千篇一律
三、设置文件 application-dev.yml

上篇文章介绍使用mybatis+druid的时间是直接在datasource下设置了数据库毗连参数,这里我们将数据库设置文件放在单独的shardingsphere-config.yml专门举行分库分表的设置
spring:
datasource:
    url: jdbc:shardingsphere:classpath:shardingsphere-config.yml
    driver-class-name: org.apache.shardingsphere.driver.ShardingSphereDriver
    druid:
      initial-size: 5
      min-idle: 10
      max-active: 20
      validation-query: SELECT 1
      filters: stat,slf4j
      # 统计 SQL 执行情况
      stat:
      merge-sql: true
      log-slow-sql: true
      slow-sql-millis: 5000
      web-stat-filter:
      #不统计这些请求数据
      exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"
      #访问监控网页的登录用户名和密码
      stat-view-servlet:
      enabled: true
      url-pattern: /druid/*
      login-username: light-druid
      login-password: light-druid

# MyBatis
mybatis:
# 搜索指定包别名
type-aliases-package: com.light.**.entity
# 配置mapper的扫描,找到所有的mapper.xml映射文件
mapper-locations: classpath*:mapper/**/*Mapper.xml
# 加载全局的配置文件
configLocation: classpath:mybatis-config.xml

logging:
level:
    org.mybatis: debug
    com.light.generator.mapper: debug
四、创建shardingsphere-config.yml

在该设置文件中设置分库分表,设置参数参考解释,完备的设置示例请参考官网ShardingSphere-JDBC设置说明
# ShardingSphere 配置模式,配置为 Standalone(独立模式)
mode:
type: Standalone
repository:
    type: JDBC # 使用 JDBC 作为注册中心,支持通过数据库持久化配置

# 配置多个数据源 ds_0 和 ds_1
dataSources:
# 数据源 ds_0 配置
ds_0:
    dataSourceClassName: com.alibaba.druid.pool.DruidDataSource# 使用 Druid 数据源连接池
    driverClassName: com.mysql.cj.jdbc.Driver# MySQL 驱动类
    url: jdbc:mysql://localhost:3306/light-db?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai&useSSL=false
    # 数据库连接 URL,配置了字符编码、时区、是否使用 SSL
    username: root# 数据库用户名
    password: 123456# 数据库密码

# 数据源 ds_1 配置
ds_1:
    dataSourceClassName: com.alibaba.druid.pool.DruidDataSource# 使用 Druid 数据源连接池
    driverClassName: com.mysql.cj.jdbc.Driver# MySQL 驱动类
    url: jdbc:mysql://localhost:3306/light-db_1?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai&useSSL=false
    # 数据库连接 URL,配置了字符编码、时区、是否使用 SSL
    username: root# 数据库用户名
    password: 123456# 数据库密码

# ShardingSphere 的分片规则
rules:
- !SHARDING# 启用分片规则
    tables:
      t_user:
      # 配置 t_user 表的分片规则
      actualDataNodes: ds_${0..1}.t_user# 定义表的实际数据节点,ds_0 和 ds_1 分别表示两个数据源
      databaseStrategy:
          standard:
            # 配置数据库的分片策略
            shardingColumn: id# 使用 id 列作为分片字段
            shardingAlgorithmName: database_inline# 使用 INLINE 算法进行分片
      keyGenerateStrategy:
          # 配置主键生成策略
          column: id# 主键列为 id
          keyGeneratorName: snowflake# 使用 Snowflake 算法生成主键

    # 配置分库算法
    shardingAlgorithms:
      database_inline:
      type: INLINE# 使用 INLINE 算法
      props:
          algorithm-expression: ds_${id % 2}# 分库算法,根据 id 字段的值做取余运算,分配到 ds_0 或 ds_1 数据源

    # 配置主键生成算法
    keyGenerators:
      snowflake:
      type: SNOWFLAKE# 使用 Snowflake 算法生成全局唯一的 ID
      props:
          worker-id: 123# 配置 Snowflake 算法的工作机器 ID,用于生成唯一的 ID

# 配置一些全局属性
props:
sql-show: true# 是否显示 SQL 执行日志,设置为 true 时会在日志中输出 SQL

完备项目结构

https://i-blog.csdnimg.cn/direct/2d99584aaace4a809f015c6a722c853f.png
五、测试

在此通过insertUser和getUserList举行测试,具体测试代码请参考我的前章节内容 八.springboot集成mybatis+druid数据库毗连池


[*]测试新增用户
https://i-blog.csdnimg.cn/direct/c1eaef084aef4136be09559266f1aa0d.png
[*]测试查询
https://i-blog.csdnimg.cn/direct/38d40d3b1346459d9f7b4ffab20dfeaa.png
此时检察2个数据库中就能看到刚刚测试添加的数据了
总结

在这篇实践中,我们使用了 ShardingSphere 配合 MyBatis 和 Druid 实现了分库分表的功能。通过设置,我们定义了分库分表策略、数据源。结合 MyBatis,我们可以在服务层举行 CRUD 操作,轻松管理数据。
这种方式不但提高了数据库的性能,还确保了数据的可扩展性,适用于大规模体系的构建。如果你有任何问题,欢迎在批评区留言。
ShardingSphere另有许多其他功能,比如数据加密、影子库、数据脱敏、读写分离等,具体说明请参考ShardingSphere官网介绍

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: 九.Spring Boot使用 ShardingSphere + MyBatis + Druid 举行分库分表