前置知识
在开始本教程之前,建议您具备以下基础知识:
- Java 基础语法
- Maven 或 Gradle 构建工具
- Spring Boot 基础
- MySQL 数据库基础
什么是 Sharding-JDBC?
Sharding-JDBC 是一个开源的分布式数据库中间件解决方案。它在 Java 的 JDBC 层提供的额外服务,可以透明化数据库分库分表访问。主要功能包括:
2025/9/17大约 4 分钟
前置知识
在开始本教程之前,建议您具备以下基础知识:
Sharding-JDBC 是一个开源的分布式数据库中间件解决方案。它在 Java 的 JDBC 层提供的额外服务,可以透明化数据库分库分表访问。主要功能包括:
前置知识
在学习本教程前,请确保您已经:
首先配置一个主库和两个从库:
spring:
shardingsphere:
datasource:
names: master,slave0,slave1
master:
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
jdbc-url: jdbc:mysql://localhost:3306/demo_master
username: root
password: root
slave0:
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
jdbc-url: jdbc:mysql://localhost:3307/demo_slave0
username: root
password: root
slave1:
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
jdbc-url: jdbc:mysql://localhost:3308/demo_slave1
username: root
password: root
rules:
readwrite-splitting:
data-sources:
readwrite_ds:
type: Static
props:
write-data-source-name: master
read-data-source-names: slave0,slave1
load-balancer-name: round_robin
load-balancers:
round_robin:
type: ROUND_ROBIN
props:
sql-show: true
前置知识
在学习本教程前,请确保您已经:
Sharding-JDBC 支持两种类型的分布式事务:
基于 XA 协议实现的强一致性分布式事务:
spring:
shardingsphere:
datasource:
names: ds0,ds1
# ... 数据源配置省略
rules:
transaction:
defaultType: XA
providerType: Atomikos
前置知识
在学习本教程前,请确保您已经:
<dependencies>
<!-- Spring Boot Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Sharding-JDBC Spring Boot Starter -->
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>shardingsphere-jdbc-core-spring-boot-starter</artifactId>
<version>5.3.2</version>
</dependency>
<!-- MyBatis Spring Boot Starter -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.3.1</version>
</dependency>
</dependencies>
前置知识
在学习本教程前,请确保您已经:
// 推荐:使用单一分片键
TableRuleConfiguration orderTableRuleConfig = new TableRuleConfiguration("t_order", "ds${0..1}.t_order${0..1}");
orderTableRuleConfig.setTableShardingStrategyConfig(
new StandardShardingStrategyConfiguration("order_id", new OrderShardingAlgorithm())
);
// 不推荐:使用多分片键,可能影响性能
TableRuleConfiguration orderTableRuleConfig = new TableRuleConfiguration("t_order", "ds${0..1}.t_order${0..1}");
orderTableRuleConfig.setTableShardingStrategyConfig(
new ComplexShardingStrategyConfiguration("order_id,user_id", new ComplexOrderShardingAlgorithm())
);