1.行表达式
使用 Groovy 语法的行表达式
t_order_${1..3} 将被转化为 t_order_1, t_order_2, t_order_3
${['online', 'offline']}_table${1..3} 将被转化为 online_table1, online_table2, online_table3, offline_table1, offline_table2, offline_table3
官方文档:
https://shardingsphere.apache.org/document/current/cn/user-manual/common-config/builtin-algorithm/expr/
2.分片算法
使用,标准分片算法-行表达式分片算法。
还有其他分片算法,如自动分片算法-取模分片算法等。
官方文档:
https://shardingsphere.apache.org/document/current/cn/user-manual/common-config/builtin-algorithm/sharding/
3.使用分布式主键
可以直接使用mybatisplus的分布式主键(雪花算法)
@TableId(type = IdType.ASSIGN_ID)//分布式主键
也可以使用shardingsphere的分布式序列算法
官方文档:
https://shardingsphere.apache.org/document/current/cn/user-manual/common-config/builtin-algorithm/keygen/
由于mybatisplus的分布式主键的优先级高于shardingsphere的分布式序列算法,所以当二者都设置的时候,实际会使用mybatisplus的分布式主键,需要将mybatisplus主键设置为自增主键,@TableId(type = IdType.AUTO),再设置shardingsphere的分布式序列算法,此时才会使用mybatisplus的分布式主键
4.创建数据库和表
创建3个数据库ds_0、ds_1、ds_2
ds_2包括user表
ds_0包括user_order_0、user_order_1表
ds_1包括user_order_0、user_order_1表
逻辑表user_order表对应4个真实表实现水平分片,ds_0库中的user_order_0、user_order_1表,ds_1库中的user_order_0、user_order_1表
5.水平分库
逻辑表user_order数据分片到实际表ds_0库中的user_order_0表、ds_1库中的user_order_0表
shardingsphereconf.yaml中添加:
...
rules:
- !SHARDING
tables:
user:
actualDataNodes: ds_2.user
user_order:
actualDataNodes: ds_${0..1}.user_order_0
defaultDatabaseStrategy:
standard:
shardingColumn: user_id
shardingAlgorithmName: database_inline
shardingAlgorithms:
database_inline:
type: INLINE
props:
algorithm-expression: ds_${user_id % 2}
...
6.水平分表
逻辑表user_order数据分片到实际表ds_0库中的user_order_0表、ds_0库中的user_order_1表
shardingsphereconf.yaml中添加:
...
rules:
- !SHARDING
tables:
user:
actualDataNodes: ds_2.user
user_order:
actualDataNodes: ds_0.user_order_${0..1}
tableStrategy:
standard:
shardingColumn: id
shardingAlgorithmName: t_order_inline
shardingAlgorithms:
t_order_inline:
type: INLINE
props:
algorithm-expression: user_order_${id % 2}
...
7.水平分库分表
逻辑表user_order数据分片到实际表ds_0库中的user_order_0表、ds_0库中的user_order_1表,ds_1库中的user_order_0表、ds_1库中的user_order_1表
shardingsphereconf.yaml中添加:
...
rules:
- !SHARDING
tables:
user:
actualDataNodes: ds_2.user
user_order:
actualDataNodes: ds_${0..1}.user_order_${0..1}
tableStrategy:
standard:
shardingColumn: id
shardingAlgorithmName: t_order_inline
defaultDatabaseStrategy:
standard:
shardingColumn: user_id
shardingAlgorithmName: database_inline
shardingAlgorithms:
database_inline:
type: INLINE
props:
algorithm-expression: ds_${user_id % 2}
t_order_inline:
type: INLINE
props:
algorithm-expression: user_order_${id % 2}
...
8.打印sql
shardingsphereconf.yaml中添加:
...
props:
sql-show: true
...
官方文档:
https://shardingsphere.apache.org/document/current/cn/user-manual/common-config/props/
9.参考代码
链接:https://pan.baidu.com/s/1SfIBRMi8xmUqL9rihh5obg?pwd=1111
提取码:1111
需要用init.sql中语句建表,更换数据库链接和账号密码