上一篇博客是将分库分表分开来使用的,本文将把分库分表结合起来使用一下
同样创建两个数据库并分别创建两张表
字段属性
yml配置文件:
spring:
shardingsphere:
datasource:
names: db1,db2
db1:
type: com.zaxxer.hikari.HikariDataSource
jdbc-url: jdbc:mysql://localhost:3306/db1?serverTimezone=GMT%2b8
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 123456
db2:
type: com.zaxxer.hikari.HikariDataSource
jdbc-url: jdbc:mysql://localhost:3306/db2?serverTimezone=GMT%2b8
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 123456
sharding:
tables:
#逻辑表名
user:
actual-data-nodes: db$->{1..2}.table_$->{[1,2]}
#actual-data-nodes: db.table_1,db.table_2
key-generator:
column: id #自定填充字段
type: SNOWFLAKE #雪花算法 UUID、SNOWFLAKE两种(实现ShardingKeyGenerator接口)
table-strategy: #分表策略
inline: #行表达式
sharding-column: id #分片键
algorithm-expression: table_$->{id % 2 + 1} #分片具体策略 id奇数存table_2,偶数存table_1
database-strategy: #分库策略
inline: #行表达式
sharding-column: sex #按性别字段分库 (0:女 1:男)
algorithm-expression: db$->{sex % 2 + 1} # 性别女存db1,男存db2
default-table-strategy:
inline:
algorithm-expression: table_$->{id % 2 + 1}
在同一个逻辑表下同时配置分库和分表策略即可,这里的分库的分片键是sex,分表的分片键是id。先按性别分库,再按id分表。
性别值1存db2、0存db1,奇数id存table_2、偶数id存table_1
测试插入:
User user = new User();
user.setName("sam");
user.setAge(22);
user.setSex(1);
userMapper.insert(user);
控制台日志:
Actual SQL: db2 ::: INSERT INTO table_2 (id, age, name, sex) VALUES (?, ?, ?, ?) ::: [1475280737322434561, 22, sam, 1]
插入的数据性别值1,生成的id值是奇数。确实按照配置分库分表策略存入对应的库中
注意事项
逻辑表名:在配置文件中配置的是逻辑表名,在代码层面sql操作的也是逻辑表名
actual-data-nodes:实际存储数据的所有表节点,由数据库+表名构成,按照配置的分库分表策略最终选择会选择一个节点
分库和分表策略
:到此我是用的都是inline(行表达式),通过表达式来匹配节点。其实还有其他的方式,standard
、complex
、hint
、none