概念介绍、建表SQL参考上文
Spring Boot 2.x 整合 ShardingSphere 5.x 实现分表
本文实现分库分表(采用shardingsphere-jdbc-core-spring-boot-starter 5.0.0正式版)
数据库展示:
SpringBoot工程引入Maven依赖
<!-- ShardingSphere -->
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>shardingsphere-jdbc-core-spring-boot-starter</artifactId>
<version>5.0.0</version>
</dependency>
application.yml配置
spring:
shardingsphere:
# 数据源配置
datasource:
# 数据源名称,多数据源以逗号分隔
names: db0,db1
db0:
# 数据库连接池类名称
type: com.zaxxer.hikari.HikariDataSource
# 数据库驱动类名
driver-class-name: com.mysql.cj.jdbc.Driver
jdbc-url: jdbc:mysql://127.0.0.1:3306/shardingsphere-demo1?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
username: root
password: root
db1:
# 数据库连接池类名称
type: com.zaxxer.hikari.HikariDataSource
# 数据库驱动类名
driver-class-name: com.mysql.cj.jdbc.Driver
jdbc-url: jdbc:mysql://127.0.0.1:3306/shardingsphere-demo2?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
username: root
password: root
# 规则配置
rules:
sharding:
# 分片算法配置
sharding-algorithms:
database-inline:
# 分片算法类型 https://shardingsphere.apache.org/document/current/cn/user-manual/shardingsphere-jdbc/configuration/built-in-algorithm/sharding/
type: INLINE
props:
# 分片算法的行表达式(算法自行定义,此处为方便演示效果)
algorithm-expression: db$->{order_id > 4?1:0}
table-inline:
# 分片算法类型 https://shardingsphere.apache.org/document/current/cn/user-manual/shardingsphere-jdbc/configuration/built-in-algorithm/sharding/
type: INLINE
props:
# 分片算法的行表达式
algorithm-expression: t_order$->{order_id % 4}
# 分布式序列算法配置
key-generators:
snowflake:
# 分布式序列算法(雪花算法:SNOWFLAKE; UUID:UUID)(注:UUID没有props配置) https://shardingsphere.apache.org/document/current/cn/user-manual/shardingsphere-jdbc/configuration/built-in-algorithm/keygen/
type: SNOWFLAKE
# 分布式序列算法属性配置
props:
# 工作机器唯一标识
worker-id: 1
tables:
# 逻辑表名称
t_order:
# 行表达式标识符可以使用 ${...} 或 $->{...},但前者与 Spring 本身的属性文件占位符冲突,因此在 Spring 环境中使用行表达式标识符建议使用 $->{...}
actual-data-nodes: db${0..1}.t_order${0..3}
# 分库策略
database-strategy:
standard:
# 分片列名称
sharding-column: order_id
# 分片算法名称
sharding-algorithm-name: database-inline
# 分表策略
table-strategy:
standard:
# 分片列名称
sharding-column: order_id
# 分片算法名称
sharding-algorithm-name: table-inline
# 属性配置
props:
# 展示修改以后的sql语句
sql-show: true
项目地址(分库分表):https://gitee.com/lemonwjh/ShardingSphere-demo