shardingjdbc分库分表实现
时间: 2023-08-31 12:09:43 浏览: 228
ShardingSphere是一个开源的分布式数据库中间件,提供分库分表、读写分离、数据加密等功能。其中,Sharding-JDBC是ShardingSphere中的一个子模块,专门用于实现分库分表功能。下面简单介绍下Sharding-JDBC的使用步骤:
1. 引入依赖
```xml
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-core</artifactId>
<version>${sharding-jdbc.version}</version>
</dependency>
```
2. 配置数据源
在`application.yml`中配置数据源信息,以MySQL为例:
```yaml
spring:
datasource:
sharding:
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: root
jdbc-url: jdbc:mysql://localhost:3306/sharding_db?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8&rewriteBatchedStatements=true
```
3. 配置分片规则
在`sharding.yml`中配置分片规则,以按照用户ID分库分表为例:
```yaml
sharding:
tables:
user:
actualDataNodes: ds$->{0..1}.user$->{0..2}
tableStrategy:
standard:
shardingColumn: user_id
preciseAlgorithmClassName: org.apache.shardingsphere.shardingalgorithm.sharding.standard.PreciseModuloShardingAlgorithm
rangeAlgorithmClassName: org.apache.shardingsphere.shardingalgorithm.sharding.standard.RangeModuloShardingAlgorithm
databaseStrategy:
standard:
shardingColumn: user_id
preciseAlgorithmClassName: org.apache.shardingsphere.shardingalgorithm.sharding.standard.PreciseModuloShardingAlgorithm
rangeAlgorithmClassName: org.apache.shardingsphere.shardingalgorithm.sharding.standard.RangeModuloShardingAlgorithm
```
其中,`actualDataNodes`指定了实际数据节点的名称,`tableStrategy`和`databaseStrategy`分别指定了表和库的分片策略。
4. 配置分布式事务
如果需要使用分布式事务,需要配置对应的事务管理器,以Atomikos为例:
```yaml
spring:
jta:
atomikos:
datasource:
xa-data-source-class-name: com.zaxxer.hikari.HikariDataSource
min-pool-size: 1
max-pool-size: 20
max-lifetime: 300000
borrow-connection-timeout: 30000
login-timeout: 3000
maintenance-interval: 60
max-idle-time: 600000
recovery:
log-file-name: txlog
recovery-dir: ./
recover-delay: 10000
max-retries: 10
```
5. 使用Sharding-JDBC
在代码中使用`ShardingDataSource`代替原来的`DataSource`,例如:
```java
@Autowired
private DataSource dataSource;
public void test() throws SQLException {
Connection conn = dataSource.getConnection();
PreparedStatement ps = conn.prepareStatement("insert into user(user_id, username) values (?, ?)");
ps.setInt(1, 1);
ps.setString(2, "test");
ps.executeUpdate();
ps.close();
conn.close();
}
```
以上就是Sharding-JDBC的基本使用方法,如果需要更加详细的配置和使用,请参考官方文档。
阅读全文