1、引入依赖
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>shardingsphere-jdbc-core-spring-boot-starter</artifactId>
<version>5.1.2</version>
</dependency>
2、springboot配置文件如下
spring:
shardingsphere:
datasource:
names: ds1,ds2,ds3
ds1:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/edu_db_1?serverTimezone=Asia/Shanghai
username: root
password: 123456
ds2:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/edu_db_2?serverTimezone=Asia/Shanghai
username: root
password: 123456
ds3:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/user_db?serverTimezone=Asia/Shanghai
username: root
password: 123456
rules:
sharding:
tables:
course:
actual-data-nodes: ds$->{1..2}.course_$->{1..2}
key-generate-strategy:
column: cid
key-generator-name: snowflake #主键生成方式
#水平分表策略
table-strategy:
standard:
sharding-column: cid
sharding-algorithm-name: course-inline #分片算法名称
#水平分库策略
database-strategy:
standard:
sharding-column: user_id
sharding-algorithm-name: database-inline
#配置垂直分库,专库专表
t_user:
actual-data-nodes: ds3.t_user
key-generate-strategy:
column: user_id
key-generator-name: snowflake
table-strategy:
standard:
sharding-column: user_id
sharding-algorithm-name: user-vertical
t_udict:
keyGenerator:
column: dict_id
type: snowflake
sharding-algorithms:
course-inline:
type: INLINE
props:
algorithm-expression: course_$->{cid%2+1} #配置分片算法对应的策略
database-inline:
type: INLINE
props:
algorithm-expression: ds$->{user_id%2+1}
user-vertical:
type: INLINE
props:
algorithm-expression: t_user
broadcast-tables:
- t_udict #配置广播表,每个数据库都有,不做分库分表
props:
sql-show: true
main:
allow-bean-definition-overriding: true
值得注意的是,使用druid连接池,连接字符串属性用url,而使用hikari连接池,连接字符串属性要用jdbc-url