PS:依赖配置看shardingsphere-jdbc第一篇
数据表
CREATE TABLE `t_order0` (
`order_id` bigint(20) NOT NULL AUTO_INCREMENT,
`order_code` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL DEFAULT '',
`user_id` int(11) DEFAULT NULL,
`amount` decimal(4,2) DEFAULT NULL,
PRIMARY KEY (`order_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;
CREATE TABLE `t_order1` (
`order_id` bigint(20) NOT NULL AUTO_INCREMENT,
`order_code` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL DEFAULT '',
`user_id` int(11) DEFAULT NULL,
`amount` decimal(4,2) DEFAULT NULL,
PRIMARY KEY (`order_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;
yml
server:
port: 8081
spring:
main:
allow-bean-definition-overriding: true
shardingsphere:
datasource:
names: ds0
ds0:
type: com.alibaba.druid.pool.DruidDataSource
driverClassName: "com.mysql.cj.jdbc.Driver"
url: jdbc:mysql://xxxx:30037/xxx?characterEncoding=UTF-8&useSSL=false&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&serverTimezone=Asia/Shanghai
username: "xxx"
password: "xxx"
sharding:
tables:
t_order:
actualDataNodes: ds0.t_order$->{0..1}
table-strategy:
inline:
sharding-column: order_id
#根据字段值求模
algorithm-expression: t_order$->{order_id % 2}
key-generator: #设置主键id生成策略
column: order_id #主键列
type: SNOWFLAKE #设置为雪花算法
props:
worker:
id: 123
max:
vibration:
offset: 1
po对象
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
import java.io.Serializable;
import java.math.BigDecimal;
@Data
@TableName("t_order") //PS:这里写的是逻辑表的名称
public class OrderPo implements Serializable {
@TableLogic("t_order")
@TableId(value = "order_id",type = IdType.AUTO)
private Long orderId;
@TableField("order_code")
private String orderCode;
@TableField("user_id")
private Integer userId;
@TableField("amount")
private BigDecimal amount;
}
mapper/service不在赘述,正常写法
测试:
@Test
void insertOrderDemo(){
//当前设置的是根据主键除模运算,主键为偶数的落t_order0,奇数的落t_order1
for (int i = 1; i <= 10; i++) {
OrderPo orderPo = new OrderPo(preCode + i, new Random().nextInt(10) + i, BigDecimal.TEN);
orderService.insert(orderPo);
}
}
inline表达式相对比较方便,不需要自己开发额外的分片算法。
列出三种常用的方式
#根据字段求模分片
t_order:
actualDataNodes: ds0.t_order$->{0..1}
table-strategy:
inline:
sharding-column: order_id
#根据字段值求模
algorithm-expression: t_order$->{order_id % 2}
#字段的hashcode求模
#algorithm-expression: t_order$->{Math.abs(order_id.hashCode()) % 2}
#根据字段哈希值进行求模分片
t_order:
actualDataNodes: ds0.t_order$->{0..1}
table-strategy:
inline:
sharding-column: order_id
#字段的hashcode求模
algorithm-expression: t_order$->{Math.abs(order_id.hashCode()) % 2}
#根据枚举值分片,如订单根据北京、上海等区域或订单类型进行分表时就很适用
t_area:
actualDataNodes: ds0.t_area_$->{['shanghai','tianjin']}
table-strategy:
inline:
sharding-column: area
#枚举算法
algorithm-expression: t_area_$->{area}