ShardingSphere 是一个开源的分布式数据库中间件解决方案组成的生态圈,其中包括 Sharding-JDBC 和 Sharding-Proxy 两个独立的产品。这里主要介绍 Sharding-JDBC 如何在 Spring Boot 项目中进行分库分表的应用和配置。
1. 引入ShardingSphere依赖
在Spring Boot项目的pom.xml
文件中引入ShardingSphere的Spring Boot Starter依赖:
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-spring-boot-starter</artifactId>
<!-- 根据实际情况填写版本号 -->
<version>5.1.1</version>
</dependency>
2. 配置数据源
在application.yml
或application.properties
中配置数据源以及ShardingSphere的分片规则:
# application.yml 示例
spring:
shardingsphere:
datasource:
names: ds0, ds1 # 数据源名称列表
ds0: # 第一个数据源配置
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: org.mariadb.jdbc.Driver
url: jdbc:mariadb://localhost:3306/db0
username: root
password: password
ds1: # 第二个数据源配置...
sharding:
tables:
your_table_name: # 分片表名
actual-data-nodes: ds$->{0..1}.your_table_name_$->{0..1} # 实际数据节点分布,假设按照分片因子分为两片,每片再分两个表
database-strategy: # 数据库分片策略
inline:
sharding-column: user_id # 分片列
algorithm-expression: ds$->{user_id % 2} # 算法表达式,假设按user_id的奇偶性分库
table-strategy: # 表分片策略
inline:
sharding-column: order_id # 分片列
algorithm-expression: your_table_name_$->{order_id % 2} # 算法表达式,假设按order_id的奇偶性分表
# ... 其他配置项
3. 使用配置好的数据源
在Spring Boot项目中,由于ShardingSphere已经实现了自动配置,所以可以直接使用@Autowired
注入DataSource
进行数据库操作:
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class YourService {
@Autowired
private DataSource dataSource;
public void someMethod() {
// 使用dataSource执行SQL查询,ShardingSphere会根据配置的分片规则自动路由
try (Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM your_table_name")) {
// 处理结果集...
} catch (SQLException e) {
// 处理异常
}
}
// ...
}
4. 自定义分片策略
如果需要自定义分片算法,可以编写自己的分片策略类并注册到Spring容器中:
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ShardingConfig {
// 假设自定义了一个精确分片算法
@Bean
public PreciseShardingAlgorithm preciseShardingAlgorithm() {
return new CustomPreciseShardingAlgorithm();
}
// 假设自定义了一个范围分片算法
@Bean
public RangeShardingAlgorithm rangeShardingAlgorithm() {
return new CustomRangeShardingAlgorithm();
}
}