shardingsphere5.1.1分表分库yaml配置 自定义策略

文章详细介绍了ApacheShardingSphere的数据分片配置,包括基本配置示例和自定义策略。通过实际配置展示了如何根据user_id和id字段对数据进行分库分表。同时,文章提到了ShardingAlgorithm的重要性,解释了如PreciseShardingAlgorithm、RangeShardingAlgorithm、HintShardingAlgorithm和ComplexKeysShardingAlgorithm等分片算法的用途和场景,强调了它们在数据库扩展、数据隔离和负载均衡等方面的作用。

前言

通过阅读官方稳定给出示例 https://shardingsphere.apache.org/document

一、基本配置示例

spring:
  sharding:
    datasource:
      names: ds0, ds1
      ds0:
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://localhost:3306/db0
        username: root
        password: root
      ds1:
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://localhost:3306/db1
        username: root
        password: root
    sharding:
      default-database-strategy:
        inline:
          sharding-column: user_id
          algorithm-expression: ds$->{user_id % 2}
      tables:
        user:
          actual-data-nodes: ds$->{0..1}.user_$->{0..1}
          database-strategy:
            inline:
              sharding-column: user_id
              algorithm-expression: ds$->{user_id % 2}
          table-strategy:
            inline:
              sharding-column: id
              algorithm-expression: user_$->{id % 2}

在该配置中,有两个数据源ds0和ds1,分别对应两个数据库db0和db1。在ShardingSphere中,通过配置actual-data-nodes属性来指定数据分片的具体情况。在这里,我们指定了user表在ds0和ds1这两个数据源中的分片情况。其中,actual-data-nodes中的$->{0..1}表示分片,即分为两个分片。

在分片策略中,我们采用了取模算法。对于user表,我们根据user_id字段的值对数据进行分片,具体的算法表达式为ds$->{user_id % 2}。这样就将user表的数据分为了两个数据源。

对于具体的分片表,我们还需要设置table-strategy,以实现分表的功能。在这里,我们根据id字段的值对数据进行分表,具体的算法表达式为user_$->{id % 2}。

二、自定义策略

官网策略规则(混合规则)

rules:
- !SHARDING
  tables: # 数据分片规则配置
    <logic_table_name> (+): # 逻辑表名称
      actualDataNodes (?): # 由数据源名 + 表名组成(参考 Inline 语法规则)
      databaseStrategy (?): # 分库策略,缺省表示使用默认分库策略,以下的分片策略只能选其一
        standard: # 用于单分片键的标准分片场景
          shardingColumn: # 分片列名称
          shardingAlgorithmName: # 分片算法名称
        complex: # 用于多分片键的复合分片场景
          shardingColumns: # 分片列名称,多个列以逗号分隔
          shardingAlgorithmName: # 分片算法名称
        hint: # Hint 分片策略
          shardingAlgorithmName: # 分片算法名称
        none: # 不分片
      tableStrategy: # 分表策略,同分库策略
      keyGenerateStrategy: # 分布式序列策略
        column: # 自增列名称,缺省表示不使用自增主键生成器
        keyGeneratorName: # 分布式序列算法名称
      auditStrategy: # 分片审计策略
        auditorNames: # 分片审计算法名称
          - <auditor_name>
          - <auditor_name>
        allowHintDisable: true # 是否禁用分片审计hint
  defaultDatabaseStrategy:
    standard:
      shardingColumn: # 分片列名称
      shardingAlgorithmName: # 分片算法名称
  # 分片算法配置
  shardingAlgorithms:
    <sharding_algorithm_name> (+): # 分片算法名称
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值