目录
- 一、简介
- 二、maven依赖
- 三、数据库
- 3.1、创建数据库
- 3.2、创建表
- 四、配置(二选一)
- 4.1、properties配置
- 4.2、yml配置
- 五、实现
- 5.1、实体层
- 5.2、持久层
- 5.3、服务层
- 5.4、测试类
- 5.4.1、保存订单数据
- 5.4.2、查询订单详情数据(关联表)
一、简介
这里的绑定表也叫关联表。指分片规则一致的主表和子表。例如:t_order 表和 t_order_item 表,均按照 order_id 分片,则此两张表互为绑定表关系。绑定表之间的多表关联查询不会出现笛卡尔积关联,关联查询效率将大大提升。
本文示例大概架构,为了讲解采用最简单的水平分表+关联表,如下图:
二、maven依赖
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.alian</groupId>
<artifactId>sharding-jdbc</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>sharding-jdbc</name>
<description>sharding-jdbc</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-spring-boot-starter</artifactId>
<version>4.1.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.15</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
有些小伙伴的 druid 可能用的是 druid-spring-boot-starter
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.6</version>
</dependency>
然后出现可能使用不了的各种问题,这个时候你只需要在主类上添加 @SpringBootApplication(exclude = {DruidDataSourceAutoConfigure.class}) 即可
package com.alian.shardingjdbc;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication(exclude = {DruidDataSourceAutoConfigure.class})
@SpringBootApplication
public class ShardingJdbcApplication {
public static void main(String[] args) {
SpringApplication.run(ShardingJdbcApplication.class, args);
}
}
三、数据库
3.1、创建数据库
CREATE DATABASE `sharding_7` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
3.2、创建表
在数据库sharding_7下面分别创建四张表:tb_order_1和tb_order_2的结构是一样的,tb_order_item_1 和 tb_order_item_2 的结构是一样的,这里 tb_order 和 tb_order_item 就是关联表。这里是订单详情表里存了订单表的order_id。
tb_order_1
CREATE TABLE `tb_order_1` (
`order_id` bigint(20) NOT NULL COMMENT '主键',
`user_id` int unsigned NOT NULL DEFAULT '0' COMMENT '用户id',
`price` int unsigned NOT NULL DEFAULT '0' COMMENT '价格(单位:分)',
`order_status` tinyint unsigned NOT NULL DEFAULT '1' COMMENT '订单状态(1:待付款,2:已付款,3:已取消)',
`order_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`title` varchar(100) NOT NULL DEFAULT '' COMMENT '订单标题',
PRIMARY KEY (`order_id`),
KEY `idx_user_id` (`user_id`),
KEY `idx_order_time` (`order_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='订单表';
tb_order_2
CREATE TABLE `tb_order_2` (
`order_id` bigint(20) NOT NULL COMMENT '主键',
`user_id` int unsigned NOT NULL DEFAULT '0' COMMENT '用户id',
`price` int unsigned NOT NULL DEFAULT '0' COMMENT '价格(单位:分)',
`order_status` tinyint unsigned NOT NULL DEFAULT '1' COMMENT '订单状态(1:待付款,2:已付款,3:已取消)',
`order_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`title` varchar(100) NOT NULL DEFAULT '' COMMENT '订单标题',
PRIMARY KEY (`order_id`),
KEY `idx_user_id` (`user_id`),
KEY `idx_order_time` (`order_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='订单表';
tb_order_item_1
CREATE TABLE `tb_order_item_1` (
`id` bigint(20) NOT NULL COMMENT '主键',
`order_id` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '订单id',
`goods_name` varchar(100) NOT NULL DEFAULT '' COMMENT '商品名称',
`price` int unsigned NOT NULL DEFAULT '0' COMMENT '单价(单位:分)',
`num` int unsigned NOT NULL DEFAULT '0' COMMENT '数量',
PRIMARY KEY (`id`),
KEY `idx_order_id` (`order_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='订单详情表';
tb_order_item_2
CREATE TABLE `tb_order_item_2` (
`id` bigint(20) NOT NULL COMMENT '主键',
`order_id` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '订单id',
`goods_name` varchar(100) NOT NULL DEFAULT '' COMMENT '商品名称',
`price` int unsigned NOT NULL DEFAULT '0' COMMENT '单价(单位:分)',
`num` int unsigned NOT NULL DEFAULT '0' COMMENT '数量',
PRIMARY KEY (`id`),
KEY `idx_order_id` (`order_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='订单详情表';
四、配置(二选一)
4.1、properties配置
application.properties
server.port=8899
server.servlet.context-path=/sharding-jdbc
# 允许定义相同的bean对象去覆盖原有的
spring.main.allow-bean-definition-overriding=true
# 数据源名称,多数据源以逗号分隔
spring.shardingsphere.datasource.names=ds1
# sharding_1数据库连接池类名称
spring.shardingsphere.datasource.ds1.type=com.alibaba.druid.pool.DruidDataSource
# sharding_1数据库驱动类名
spring.shardingsphere.datasource.ds1.driver-class-name=com.mysql.cj.jdbc.Driver
# sharding_1数据库url连接
spring.shardingsphere.datasource.ds1.url=jdbc:mysql://192.168.0.129:3306/sharding_7?serverTimezone=GMT%2B8&characterEncoding=utf8&useUnicode=true&useSSL=false&zeroDateTimeBehavior=CONVERT_TO_NULL&autoReconnect=true&allowMultiQueries=true&failOverReadOnly=false&connectTimeout=6000&maxReconnects=5
# sharding_1数据库用户名
spring.shardingsphere.datasource.ds1.username=alian
# sharding_1数据库密码
spring.shardingsphere.datasource.ds1.password=123456
# 指定tb_order表的数据分布情况,配置数据节点,使用Groovy的表达式,逻辑表tb_order对应的节点是:ds1.tb_order_1, ds1.tb_order_2
spring.shardingsphere.sharding.tables.tb_order.actual-data-nodes=ds1.tb_order_$->{1..2}
# 采用行表达式分片策略:InlineShardingStrategy
# 指定tb_order表的分片策略中的分片键
spring.shardingsphere.sharding.tables.tb_order.table-strategy.inline.sharding-column=order_id
# 指定tb_order表的分片策略中的分片算法表达式,使用Groovy的表达式
spring.shardingsphere.sharding.tables.tb_order.table-strategy.inline.algorithm-expression=tb_order_$->{order_id%2==0?2:1}
# 指定tb_order表的主键为order_id
spring.shardingsphere.sharding.tables.tb_order.key-generator.column=order_id
# 指定tb_order表的主键生成策略为SNOWFLAKE
spring.shardingsphere.sharding.tables.tb_order.key-generator.type=SNOWFLAKE
# 指定雪花算法的worker.id
spring.shardingsphere.sharding.tables.tb_order.key-generator.props.worker.id=124
# 指定雪花算法的max.tolerate.time.difference.milliseconds
spring.shardingsphere.sharding.tables.tb_order.key-generator.props.max.tolerate.time.difference.milliseconds=20
# 指定tb_order_item表的数据分布情况,配置数据节点,使用Groovy的表达式,逻辑表tb_order_item对应的节点是:ds1.tb_order_item_1, ds1.tb_order_item_2
spring.shardingsphere.sharding.tables.tb_order_item.actual-data-nodes=ds1.tb_order_item_$->{1..2}
# 采用行表达式分片策略:InlineShardingStrategy
# 指定tb_order_item表的分片策略中的分片键
spring.shardingsphere.sharding.tables.tb_order_item.table-strategy.inline.sharding-column=order_id
# 指定tb_order_item表的分片策略中的分片算法表达式,使用Groovy的表达式
spring.shardingsphere.sharding.tables.tb_order_item.table-strategy.inline.algorithm-expression=tb_order_item_$->{order_id%2==0?2:1}
# 指定tb_order_item表的主键为order_id
spring.shardingsphere.sharding.tables.tb_order_item.key-generator.column=id
# 指定tb_order_item表的主键生成策略为SNOWFLAKE
spring.shardingsphere.sharding.tables.tb_order_item.key-generator.type=SNOWFLAKE
# 指定雪花算法的worker.id
spring.shardingsphere.sharding.tables.tb_order_item.key-generator.props.worker.id=125
# 指定雪花算法的max.tolerate.time.difference.milliseconds
spring.shardingsphere.sharding.tables.tb_order_item.key-generator.props.max.tolerate.time.difference.milliseconds=20
# tb_order和tb_order_item是绑定表
spring.shardingsphere.sharding.binding-tables[0]=tb_order,tb_order_item
# 打开sql输出日志
spring.shardingsphere.props.sql.show=true
4.2、yml配置
application.yml
server:
port: 8899
servlet:
context-path: /sharding-jdbc
spring:
main:
# 允许定义相同的bean对象去覆盖原有的
allow-bean-definition-overriding: true
shardingsphere:
props:
sql:
# 打开sql输出日志
show: true
datasource:
# 数据源名称,多数据源以逗号分隔
names: ds1
ds1:
# 数据库连接池类名称
type: com.alibaba.druid.pool.DruidDataSource
# 数据库驱动类名
driver-class-name: com.mysql.cj.jdbc.Driver
# 数据库url连接
url: jdbc:mysql://192.168.0.129:3306/sharding_7?serverTimezone=GMT%2B8&characterEncoding=utf8&useUnicode=true&useSSL=false&zeroDateTimeBehavior=CONVERT_TO_NULL&autoReconnect=true&allowMultiQueries=true&failOverReadOnly=false&connectTimeout=6000&maxReconnects=5
# 数据库用户名
username: alian
# 数据库密码
password: 123456
sharding:
# 未配置分片规则的表将通过默认数据源定位
default-data-source-name: ds1
tables:
tb_order:
# 由数据源名 + 表名组成,以小数点分隔。多个表以逗号分隔,支持inline表达式
actual-data-nodes: ds1.tb_order_$->{1..2}
# 分表策略
table-strategy:
# 行表达式分片策略
inline:
# 分片键
sharding-column: order_id
# 算法表达式
algorithm-expression: tb_order_$->{order_id%2==0?2:1}
# key生成器
key-generator:
# 自增列名称,缺省表示不使用自增主键生成器
column: order_id
# 自增列值生成器类型,缺省表示使用默认自增列值生成器(SNOWFLAKE/UUID)
type: SNOWFLAKE
# SnowflakeShardingKeyGenerator
props:
# SNOWFLAKE算法的worker.id
worker:
id: 100
# SNOWFLAKE算法的max.tolerate.time.difference.milliseconds
max:
tolerate:
time:
difference:
milliseconds: 20
tb_order_item:
# 由数据源名 + 表名组成,以小数点分隔。多个表以逗号分隔,支持inline表达式
actual-data-nodes: ds1.tb_order_item_$->{1..2}
# 分表策略
table-strategy:
# 行表达式分片策略
inline:
# 分片键
sharding-column: order_id
# 算法表达式
algorithm-expression: tb_order_item_$->{order_id%2==0?2:1}
# key生成器
key-generator:
# 自增列名称,缺省表示不使用自增主键生成器
column: id
# 自增列值生成器类型,缺省表示使用默认自增列值生成器(SNOWFLAKE/UUID)
type: SNOWFLAKE
# SnowflakeShardingKeyGenerator
props:
# SNOWFLAKE算法的worker.id
worker:
id: 101
# SNOWFLAKE算法的max.tolerate.time.difference.milliseconds
max:
tolerate:
time:
difference:
milliseconds: 20
binding-tables:
- tb_order,tb_order_item
- 这里演示没分库,就是水平分表
- 对于逻辑表 tb_order, actual-data-nodes 使用Groovy的表达式 ds1.tb_order_$->{1…2},对应的物理表是:ds1.tb_order_1、 ds1.tb_order_2
- 对于逻辑表 tb_order_item, actual-data-nodes 使用Groovy的表达式 ds1.tb_order_item_$->{1…2},对应的物理表是:ds1.tb_order_item_1、 ds1.tb_order_item_2
- table-strategy 表的分片策略,这里只是一个简单的奇数偶数,采用的是 行表达式分片策略 ,需要指定分片键和分片算法表达式(算法支持Groovy的表达式),这里 tb_order 和 tb_order_item 都是使用相同的键进行分片,这里是order_id (一定不要搞错)
- key-generator :key生成器,需要指定字段和类型,比如这里如果是SNOWFLAKE,最好也配置下props中的两个属性: worker.id 与 max.tolerate.time.difference.milliseconds 属性
五、实现
5.1、实体层
Order.java
@Data
@Entity
@Table(name = "tb_order")
public class Order implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "order_id")
private Long orderId;
@Column(name = "user_id")
private Integer userId;
@Column(name = "price")
private Integer price;
@Column(name = "order_status")
private Integer orderStatus;
@Column(name = "title")
private String title;
@Column(name = "order_time")
private LocalDateTime orderTime;
}
OrderItem.java
@Data
@Entity
@Table(name = "tb_order_item")
public class OrderItem implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name = "order_id")
private Long orderId;
@ManyToOne
@JoinColumn(name = "order_id", referencedColumnName = "order_id", updatable = false, insertable = false)
private Order order;
@Column(name = "goods_name")
private String goodsName;
@Column(name = "price")
private Integer price;
@Column(name = "num")
private Integer num;
}
5.2、持久层
OrderRepository.java
public interface OrderRepository extends PagingAndSortingRepository<Order, Long> {
/**
* 根据订单id查询订单
* @param orderId
* @return
*/
Order findOrderByOrderId(Long orderId);
}
OrderItemRepository.java
public interface OrderItemRepository extends PagingAndSortingRepository<OrderItem, Long> {
/**
* 根据用户orderId查询订单详情
*
* @param orderId
* @return
*/
List<OrderItem> findAllByOrderId(Long orderId);
}
5.3、服务层
OrderService.java
@Slf4j
@Service
public class OrderService {
@Autowired
private OrderRepository orderRepository;
public void saveOrder(Order order) {
orderRepository.save(order);
}
public Order queryOrder(Long orderId) {
return orderRepository.findOrderByOrderId(orderId);
}
}
OrderItemService.java
@Slf4j
@Service
public class OrderItemService {
@Autowired
private OrderItemRepository orderItemRepository;
public void saveOrderItem(OrderItem orderItem) {
orderItemRepository.save(orderItem);
}
public List<OrderItem> queryOrderItem(Long orderId) {
return orderItemRepository.findAllByOrderId(orderId);
}
}
5.4、测试类
OrderTests.java
@Slf4j
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class OrderTests {
@Autowired
private OrderService orderService;
@Autowired
private OrderItemService orderItemService;
@Test
public void saveOrder() {
for (int i = 0; i < 10; i++) {
Order order = new Order();
OrderItem orderItem = new OrderItem();
// 随机生成50到100的金额
int price = (int) Math.round(Math.random() * (10000 - 5000) + 5000);
// 随机生成1到10的数量
int num = (int) Math.round(Math.random() * (10 - 1) + 1);
orderItem.setPrice(price);
orderItem.setNum(num);
orderItem.setGoodsName("商品-" + price);
order.setUserId(1000);
order.setPrice(price * num);
order.setOrderStatus(2);
order.setOrderTime(LocalDateTime.now());
order.setTitle("");
orderService.saveOrder(order);
// 设置orderId
log.info("订单id:{}", order.getOrderId());
orderItem.setOrderId(order.getOrderId());
orderItem.setOrder(order);
orderItemService.saveOrderItem(orderItem);
}
}
@Test
public void queryOrder() {
Long orderId = 847575584761856000L;
List<OrderItem> orderItemList = orderItemService.queryOrderItem(orderId);
log.info("查询的结果:{}", orderItemList);
}
}
5.4.1、保存订单数据
效果图:
从上面的数据来看,tb_order_1的关联数据都在tb_order_item_1 中,tb_order_2的关联数据都在tb_order_item_2 中,这样就可以避免掉笛卡尔积。具体的我们看下查询。
5.4.2、查询订单详情数据(关联表)
20:53:20 526 INFO [main]:Logic SQL: select orderitem0_.id as id1_1_, orderitem0_.goods_name as goods_na2_1_, orderitem0_.num as num3_1_, orderitem0_.order_id as order_id4_1_, orderitem0_.price as price5_1_ from tb_order_item orderitem0_ where orderitem0_.order_id=?
20:53:20 526 INFO [main]:Actual SQL: ds1 ::: select orderitem0_.id as id1_1_, orderitem0_.goods_name as goods_na2_1_, orderitem0_.num as num3_1_, orderitem0_.order_id as order_id4_1_, orderitem0_.price as price5_1_ from tb_order_item_2 orderitem0_ where orderitem0_.order_id=? ::: [847575584761856000]
20:53:20 566 INFO [main]:Logic SQL: select order0_.order_id as order_id1_0_0_, order0_.order_status as order_st2_0_0_, order0_.order_time as order_ti3_0_0_, order0_.price as price4_0_0_, order0_.title as title5_0_0_, order0_.user_id as user_id6_0_0_ from tb_order order0_ where order0_.order_id=?
20:53:20 566 INFO [main]:Actual SQL: ds1 ::: select order0_.order_id as order_id1_0_0_, order0_.order_status as order_st2_0_0_, order0_.order_time as order_ti3_0_0_, order0_.price as price4_0_0_, order0_.title as title5_0_0_, order0_.user_id as user_id6_0_0_ from tb_order_2 order0_ where order0_.order_id=? ::: [847575584761856000]
20:53:20 580 INFO [main]:查询的结果:[OrderItem(id=847575584870912000, orderId=847575584761856000, order=Order(orderId=847575584761856000, userId=1000, price=45130, orderStatus=2, title=, orderTime=2023-03-28T20:42:47), goodsName=商品-9026, price=9026, num=5)]
从上面的结果我们可以看到当我们查询order_id为 847575584761856000 的记录时,因为我们之前是按 order_id 进行的分表,偶数直接查询 tb_order_item_2 ,查询到订单详情记录后,关联查询订单记录,就直接查询 tb_order_2 ,都是主键或索引查询,没有出现笛卡尔积式的查询,提高了效率。