SpringBoot 集成 sharding-jdbc-spring-boot-starter 并使用 yml 配置多数据源的方式 进行 分表配置
时间: 2023-09-20 13:08:13 浏览: 153
好的,下面是 SpringBoot 集成 sharding-jdbc-spring-boot-starter 并使用 yml 配置多数据源的方式 进行 分表配置的步骤:
1. 首先,在 pom.xml 文件中添加 sharding-jdbc-spring-boot-starter 依赖,如下所示:
```xml
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-spring-boot-starter</artifactId>
<version>${shardingsphere.version}</version>
</dependency>
```
2. 在 application.yml 配置文件中添加数据源配置,如下所示:
```yml
spring:
datasource:
# 主数据源
master:
url: jdbc:mysql://localhost:3306/db_master?serverTimezone=UTC&useSSL=false&characterEncoding=utf-8
username: root
password: root
# 从数据源
slave:
url: jdbc:mysql://localhost:3306/db_slave?serverTimezone=UTC&useSSL=false&characterEncoding=utf-8
username: root
password: root
# sharding-jdbc 配置
sharding:
jdbc:
#配置主从数据源名称
data-sources:
# 配置主数据源
master:
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.jdbc.Driver
jdbc-url: ${spring.datasource.master.url}
username: ${spring.datasource.master.username}
password: ${spring.datasource.master.password}
hikari:
minimum-idle: 5
maximum-pool-size: 20
auto-commit: true
idle-timeout: 30000
pool-name: master
# 配置从数据源
slave:
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.jdbc.Driver
jdbc-url: ${spring.datasource.slave.url}
username: ${spring.datasource.slave.username}
password: ${spring.datasource.slave.password}
hikari:
minimum-idle: 5
maximum-pool-size: 20
auto-commit: true
idle-timeout: 30000
pool-name: slave
# 配置表规则
sharding:
tables:
# 配置分表规则
user:
actual-data-nodes: master.user_${0..2}
table-strategy:
inline:
sharding-column: id
algorithm-expression: user_${id % 3}
key-generator:
type: SNOWFLAKE
column: id
props:
worker-id: 123
# 配置读写分离规则
master-slave-rules:
- name: ms
master-data-source-name: master
slave-data-source-names: slave
```
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, age) values(?, ?, ?)";
Object[] params = new Object[]{user.getId(), user.getName(), user.getAge()};
jdbcTemplate.update(sql, params);
}
@Override
public List<User> getUsers() {
String sql = "select * from user";
List<User> userList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class));
return userList;
}
}
```
希望这些步骤能够帮助你集成 sharding-jdbc-spring-boot-starter 并使用 yml 配置多数据源的方式进行分表配置。如果你有更多的问题,欢迎随时向我提问。
阅读全文