springboot引入shardingsphere-jdbc-core实现分库分表
时间: 2023-09-25 11:15:30 浏览: 161
spring boot整合sharding jdbc5.2.0分库分表demo
1. 引入依赖
在 `pom.xml` 中引入 `shardingsphere-jdbc-core` 依赖:
```xml
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>shardingsphere-jdbc-core</artifactId>
<version>5.0.0-alpha</version>
</dependency>
```
2. 配置数据源
在 `application.yml` 中配置数据源:
```yaml
spring:
datasource:
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8
username: root
password: root
sharding:
jdbc:
# 数据源列表
datasource:
ds0:
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.jdbc.Driver
jdbc-url: jdbc:mysql://localhost:3306/test0?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8
username: root
password: root
ds1:
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.jdbc.Driver
jdbc-url: jdbc:mysql://localhost:3306/test1?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8
username: root
password: root
# 分片规则配置
sharding:
default-data-source: ds0 # 默认数据源
tables:
user:
actual-data-nodes: ds${0..1}.user_${0..1} # 实际数据节点
database-strategy:
inline:
sharding-column: id # 分片键
algorithm-expression: ds${id % 2} # 分库算法
table-strategy:
inline:
sharding-column: id # 分片键
algorithm-expression: user_${id % 2} # 分表算法
```
3. 编写代码
```java
@Service
public class UserServiceImpl implements UserService {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public void addUser(User user) {
String sql = "INSERT INTO user (id, name) VALUES (?, ?)";
Object[] params = new Object[] { user.getId(), user.getName() };
int count = jdbcTemplate.update(sql, params);
System.out.println("插入 " + count + " 条记录");
}
@Override
public List<User> getUsers() {
String sql = "SELECT * FROM user";
return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class));
}
}
```
4. 测试
编写测试方法:
```java
@SpringBootTest
class UserServiceImplTest {
@Autowired
private UserService userService;
@Test
void addUser() {
User user = new User();
user.setId(1L);
user.setName("张三");
userService.addUser(user);
}
@Test
void getUsers() {
List<User> users = userService.getUsers();
System.out.println(users);
}
}
```
执行测试方法,查看控制台输出和数据库表中的数据,验证分库分表是否成功实现。
阅读全文