配置示例
spring:
application:
name: app
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://ip:13306/mall-goods
username: root
password: njnu@liyong
jpa:
database: mysql
hibernate:
ddl-auto: none
show-sql: true
shardingsphere:
mode:
overwrite: true
repository:
type: JDBC
type: Standalone
# 数据源配置
datasource:
# 数据源名称,多数据源以逗号分隔
db0:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://ip:13306/mall_0
username: root
password: njnu@liyong
db1:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://ip:23306/mall_1
username: root
password: njnu@liyong
names: db0,db1
# 分片规则配置
rules:
sharding:
# 分片算法配置
sharding-algorithms:
database-inline:
# 分片算法类型
type: INLINE
props:
# 分片算法的行表达式(算法自行定义,此处为方便演示效果)
algorithm-expression: db$->{user_id % 2}
table-inline:
# 分片算法类型
type: INLINE
props:
# 分片算法的行表达式
algorithm-expression: t_order_$->{order_id % 2}
tables:
# 逻辑表名称
t_order:
keyGenerateStrategy:
column: order_id
key-generator-name: snowflake
# 行表达式标识符可以使用 ${...} 或 $->{...},但前者与 Spring 本身的属性文件占位符冲突,因此在 Spring 环境中使用行表达式标识符建议使用 $->{...}
actual-data-nodes: db${0..1}.t_order_${0..1}
# 分库策略
database-strategy:
standard:
# 分片列名称
sharding-column: user_id
# 分片算法名称
sharding-algorithm-name: database-inline
# 分表策略
table-strategy:
standard:
# 分片列名称
sharding-column: order_id
# 分片算法名称
sharding-algorithm-name: table-inline
#如果不配置key-generators会有错误 Caused by: java.lang.IllegalStateException: Can not find keyGenerator xxx in database logic_db .
key-generators:
snowflake:
type: SNOWFLAKE
# 属性配置
props:
# 展示修改以后的sql语句
sql-show: true
依赖如下:
<groupId>org.apache.shardingsphere</groupId>
<artifactId>shardingsphere-jdbc-core-spring-boot-starter</artifactId>
<version>5.2.1</version>
</dependency>