若依框架集成sharding-jdbc实现单库分表详细流程
时间: 2023-08-11 17:31:14 浏览: 233
shardingsphere-jdbc实现简单的单库分表
好的,下面是详细流程:
1. 引入Sharding-JDBC依赖
在pom.xml文件中添加Sharding-JDBC的依赖:
```xml
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-core</artifactId>
<version>4.1.1</version>
</dependency>
```
2. 配置数据源
在application.yml中配置数据源信息,如下所示:
```yaml
spring:
datasource:
# 主库
master:
url: jdbc:mysql://localhost:3306/db_master?serverTimezone=UTC&useSSL=false&characterEncoding=utf-8
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
# 从库
slave:
url: jdbc:mysql://localhost:3306/db_slave?serverTimezone=UTC&useSSL=false&characterEncoding=utf-8
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
shardingsphere:
datasource:
names: master,slave
# 配置主从库
master-slave-rules:
ms:
master-data-source-name: master
slave-data-source-names: slave
load-balance-algorithm-type: round_robin
# 配置数据分片规则
sharding:
tables:
user_info:
# 分库键
database-strategy:
inline:
sharding-column: user_id
algorithm-expression: ds${user_id % 2}
# 分表键
table-strategy:
inline:
sharding-column: order_id
algorithm-expression: t_order_${order_id % 2}
actual-data-nodes: master.user_info_$->{0..1}
key-generator:
column: id
type: SNOWFLAKE
```
3. 创建数据表
创建两个数据库db_master和db_slave,每个数据库中创建user_info表,表结构如下:
```sql
CREATE TABLE `user_info` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`user_id` bigint(20) NOT NULL COMMENT '用户ID',
`order_id` bigint(20) NOT NULL COMMENT '订单ID',
`name` varchar(50) NOT NULL COMMENT '姓名',
`age` int(11) NOT NULL COMMENT '年龄',
`address` varchar(200) DEFAULT NULL COMMENT '地址',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COMMENT='用户信息表';
```
4. 测试分库分表
在代码中使用Sharding-JDBC进行数据库操作,如下所示:
```java
@Service
public class UserService {
@Autowired
private JdbcTemplate jdbcTemplate;
public void addUser(UserInfo userInfo) {
String sql = "INSERT INTO user_info (user_id,order_id,name,age,address) VALUES (?,?,?,?,?)";
Object[] params = new Object[]{userInfo.getUserId(), userInfo.getOrderId(), userInfo.getName(), userInfo.getAge(), userInfo.getAddress()};
jdbcTemplate.update(sql, params);
}
public List<UserInfo> getUserList() {
String sql = "SELECT * FROM user_info";
List<UserInfo> userList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(UserInfo.class));
return userList;
}
}
```
以上就是使用Sharding-JDBC实现单库分表的详细流程。
阅读全文