springboot整合shardingsphere-jdbc
时间: 2025-06-17 16:48:38 浏览: 24
### Spring Boot 集成 ShardingSphere-JDBC 示例教程
#### 1. 引入依赖
在 `pom.xml` 文件中添加 ShardingSphere-JDBC 的 Maven 依赖。以下是一个示例配置[^3]:
```xml
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-spring-boot-starter</artifactId>
<version>5.1.1</version>
</dependency>
```
确保引入的版本与项目兼容,并根据实际需求选择合适的版本。
---
#### 2. 配置数据源
在 `application.yml` 中配置数据源和分片规则。以下是一个简单的分片配置示例[^3]:
```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/db0?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/db1?serverTimezone=UTC&useSSL=false
username: root
password: root
rules:
sharding:
tables:
t_order:
actual-data-nodes: ds$->{0..1}.t_order_$->{0..1}
table-strategy:
standard:
sharding-column: order_id
sharding-algorithm-name: t_order_inline
key-generate-strategy:
column: order_id
key-generator-name: snowflake
sharding-algorithms:
t_order_inline:
type: INLINE
props:
algorithm-expression: t_order_$->{order_id % 2}
key-generators:
snowflake:
type: SNOWFLAKE
props:
worker-id: 123
```
上述配置中,定义了两个数据源 `ds0` 和 `ds1`,并将表 `t_order` 按照 `order_id` 的奇偶性进行分片。
---
#### 3. 启动类配置
在 Spring Boot 的启动类上添加 `@MapperScan` 注解以扫描 MyBatis 的 Mapper 接口。以下是一个示例[^1]:
```java
package com.example.demo;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.example.demo.mapper")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
```
---
#### 4. 测试读写分离功能
通过编写单元测试验证读写分离功能是否正常工作。以下是一个简单的测试代码[^2]:
```java
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import lombok.extern.slf4j.Slf4j;
import java.util.List;
@SpringBootTest
@Slf4j
public class ShardingSphereTest {
@Autowired
private UserService userService;
@Test
public void testRead() {
List<User> users = userService.list();
log.info("查询结果为:{}", users);
}
@Test
public void testWrite() {
User user = new User();
user.setName("TestUser");
user.setAge(25);
userService.save(user);
log.info("插入用户成功:{}", user);
}
}
```
---
#### 5. 注意事项
- **分片算法**:ShardingSphere 提供多种内置分片算法(如 `INLINE`, `MOD`),也可以自定义分片策略[^3]。
- **数据一致性**:在分布式环境下,需特别关注数据一致性问题,例如主键生成策略、事务管理等。
- **监控与日志**:可以通过配置日志或使用 ShardingSphere 的监控工具来跟踪 SQL 执行情况。
---
阅读全文
相关推荐


















