分库分表:ShardingSphere + MySQL
时间: 2025-06-13 16:55:15 浏览: 24
### ShardingSphere 分库分表 MySQL 实现与配置教程
ShardingSphere 是一个开源的分布式数据库中间件,支持通过分库分表实现数据水平扩展[^1]。以下详细介绍了如何使用 ShardingSphere 和 MySQL 实现分库分表的配置与实现。
#### 1. 环境准备
在开始配置之前,确保已安装并运行以下环境:
- JDK 8 或更高版本。
- MySQL 数据库(建议版本 5.7 或 8.0)。
- Apache ShardingSphere(推荐使用最新稳定版本)。
此外,可以通过 ShardingSphere-JDBC 或 ShardingSphere-Proxy 来接入系统。ShardingSphere-JDBC 是以 Java 驱动的方式嵌入到应用中,而 ShardingSphere-Proxy 则是以独立服务的形式存在[^2]。
#### 2. 数据库和表结构设计
假设需要将日志表 `log` 按照日期进行分片,并且数据存储在两个数据库 `ds0` 和 `ds1` 中。每个数据库中包含多个分片表 `log_YYYYMMDD`。
```sql
-- 在 ds0 中创建表
CREATE TABLE log_202301 (
id BIGINT PRIMARY KEY,
content VARCHAR(255),
created_date DATE
);
-- 在 ds1 中创建表
CREATE TABLE log_202302 (
id BIGINT PRIMARY KEY,
content VARCHAR(255),
created_date DATE
);
```
#### 3. 数据源配置
ShardingSphere 的核心是数据源配置,定义了分库规则和分表规则。以下是基于 Spring Boot 的配置示例[^4]:
```yaml
spring:
shardingsphere:
datasource:
names: ds0,ds1
ds0:
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
jdbc-url: jdbc:mysql://localhost:3306/test?serverTimezone=UTC&useSSL=false
username: root
password: root
ds1:
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
jdbc-url: jdbc:mysql://localhost:3306/test1?serverTimezone=UTC&useSSL=false
username: root
password: root
```
#### 4. 分片规则配置
分片规则定义了数据如何分布到不同的数据库和表中。以下是一个典型的分片规则配置[^3]:
```yaml
rules:
sharding:
tables:
log:
actual-data-nodes: ds${0..1}.log_${2023..2024}${01..12}
table-strategy:
standard:
sharding-column: created_date
sharding-algorithm-name: log-table-algorithm
database-strategy:
standard:
sharding-column: created_date
sharding-algorithm-name: log-database-algorithm
sharding-algorithms:
log-database-algorithm:
type: INLINE
props:
algorithm-expression: ds${created_date.format('yyyy') % 2}
log-table-algorithm:
type: INLINE
props:
algorithm-expression: log_${created_date.format('yyyyMM')}
```
上述配置表示:
- 数据库按照 `created_date` 的年份取模分配到 `ds0` 或 `ds1`。
- 表按照 `created_date` 的年月生成对应的分片表名称。
#### 5. 测试验证
完成配置后,可以通过 SQL 查询验证分片规则是否生效。例如:
```sql
INSERT INTO log (id, content, created_date) VALUES (1, 'Test Log', '2023-01-15');
INSERT INTO log (id, content, created_date) VALUES (2, 'Test Log', '2023-02-20');
SELECT * FROM log WHERE created_date = '2023-01-15';
SELECT * FROM log WHERE created_date = '2023-02-20';
```
查询结果应分别从 `ds0.log_202301` 和 `ds1.log_202302` 返回数据。
#### 6. 注意事项
- 确保数据库和表已经按照分片规则预先创建好。
- 分片键的选择至关重要,通常选择查询条件中频繁使用的字段作为分片键[^3]。
- 如果需要读写分离,可以结合 ShardingSphere 的读写分离功能进行配置[^1]。
---
阅读全文
相关推荐




















