前言
通过阅读官方稳定给出示例 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> (+): # 分片算法名称

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

被折叠的 条评论
为什么被折叠?



