Spring Boot 中集成ShardingSphere-JDBC的基本使用
在 Spring Boot 中集成 ShardingSphere-JDBC,可以透明地将数据分片、读写分离等功能引入到应用中,而无需大规模修改业务代码。以下是在 Spring Boot 中使用 ShardingSphere 的基本步骤和核心概念。
核心概念
在开始之前,了解几个 ShardingSphere 的基本术语至关重要:
- 逻辑表 (Logical Table):应用程序代码中操作的表的名称,例如
t_order
。 - 真实表 (Actual Table):物理数据库中真实存在的表,例如分布在不同数据库中的
t_order_0
,t_order_1
。 - 分片键 (Sharding Key):用于决定数据属于哪个分片的表列,常见的如
user_id
,order_id
。 - 分片算法 (Sharding Algorithm):用于路由数据的逻辑,例如基于取模运算
sharding_key_value % number_of_shards
。
ShardingSphere-JDBC 的魅力在于它会拦截应用程序的 SQL 请求,并根据配置的规则将其路由到正确的真实数据源和真实表中执行。
基本使用步骤
1. 添加 Maven 依赖
首先,在 Spring Boot 项目的 pom.xml
文件中添加 ShardingSphere 的官方 Spring Boot Starter 依赖。
<dependency><groupId>org.apache.shardingsphere</groupId><artifactId>shardingsphere-jdbc-core-spring-boot-starter</artifactId><version>5.5.0</version> <!-- 建议使用最新稳定版 -->
</dependency>
<!-- 还需要添加数据库驱动和JPA/MyBatis等依赖 -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope>
</dependency>
2. 配置文件 (application.yml
)
接下来,在 application.yml
(或 application.properties
) 文件中进行配置。这是集成工作的核心部分,主要包括数据源配置和分片规则配置。
以下是一个将 t_order
表水平分片到两个数据库 (ds0
, ds1
),每个数据库中又分为两张表 (t_order_0
, t_order_1
) 的示例。
spring:shardingsphere:# 开启 SQL 日志,便于调试props:sql-show: true# 1. 定义真实数据源datasource:names: ds0, ds1# 第一个数据源ds0:type: com.zaxxer.hikari.HikariDataSourcedriver-class-name: com.mysql.cj.jdbc.Driverjdbc-url: jdbc:mysql://localhost:3306/ds0?useSSL=falseusername: rootpassword: your_password# 第二个数据源ds1:type: com.zaxxer.hikari.HikariDataSourcedriver-class-name: com.mysql.cj.jdbc.Driverjdbc-url: jdbc:mysql://localhost:3307/ds1?useSSL=false # 注意端口或地址不同username: rootpassword: your_password# 2. 定义规则rules:# 分片规则sharding:tables:# 配置 t_order 表的规则t_order:# 数据节点:逻辑表 t_order 映射到 ds0 和 ds1 的 t_order_0 和 t_order_1 表actual-data-nodes: ds$->{0..1}.t_order_$->{0..1}# 分库策略database-strategy:standard:sharding-column: user_id # 分库键sharding-algorithm-name: database_inline # 分库算法名称# 分表策略table-strategy:standard:sharding-column: order_id # 分表键sharding-algorithm-name: table_inline # 分表算法名称# 3. 定义分片算法sharding-algorithms:# 数据库分片算法:基于 user_id 取模database_inline:type: INLINEprops:algorithm-expression: ds$->{user_id % 2}# 表分片算法:基于 order_id 取模table_inline:type: INLINEprops:algorithm-expression: t_order_$->{order_id % 2}
配置解释:
spring.shardingsphere.datasource.names
: 声明所有真实数据源的名称。spring.shardingsphere.rules.sharding.tables
: 配置需要分片的表。actual-data-nodes
: 这是核心映射关系。ds$->{0..1}.t_order_$->{0..1}
是一种 Groovy 表达式,表示t_order
表分布在ds0.t_order_0
,ds0.t_order_1
,ds1.t_order_0
,ds1.t_order_1
这四张真实表中。database-strategy
和table-strategy
: 分别定义分库和分表的策略。这里使用的是标准策略 (standard
)。sharding-column
: 指定用于计算分片的列。sharding-algorithms
: 定义具体的分片算法。INLINE
是一种行内表达式算法,适用于简单的分片逻辑。
3. 创建实体类和 Repository
ShardingSphere 对业务代码是无侵入的,因此你可以像往常一样使用 JPA、MyBatis 等 ORM 框架。
实体类 (Entity):
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;@Entity
@Table(name = "t_order") // 使用逻辑表名
public class Order {@Idprivate Long orderId;private Long userId;private String description;// Getters and Setters
}
数据访问接口 (Repository):```java
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface OrderRepository extends JpaRepository<Order, Long> {
}```
4. 在业务逻辑中使用
在你的服务层中,直接注入 OrderRepository
并使用即可。ShardingSphere 会在底层自动处理数据的路由。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;@Service
public class OrderService {@Autowiredprivate OrderRepository orderRepository;public void createOrders() {for (int i = 0; i < 10; i++) {Order order = new Order();order.setOrderId((long) i);order.setUserId((long) (i % 4)); // 模拟不同的用户order.setDescription("Order for user " + order.getUserId());orderRepository.save(order);}}
}
当 orderRepository.save(order)
被调用时:
- ShardingSphere-JDBC 拦截该 SQL 操作。
- 它会解析出
user_id
和order_id
的值。 - 根据
application.yml
中配置的database_inline
算法 (ds${user_id % 2}
),决定数据应存入ds0
还是ds1
。 - 根据
table_inline
算法 (t_order_${order_id % 2}
),决定数据应存入t_order_0
还是t_order_1
。 - 最终,SQL 被路由到正确的物理表中执行。
通过以上步骤,我们就可以在 Spring Boot 项目中成功集成并基础地使用 ShardingSphere-JDBC 实现数据分片。ShardingSphere 还支持读写分离、数据加密和分布式事务等更高级的功能,这些也可以通过类似的配置文件进行启用和设置。