在使用shard-jdbc遇到问题,4.x版本和5.x版本相差很大,配置基本上不能复用。
- 在使用4.x的时候,maven仓库中的最新版本是4.1.1,使用的依赖:
<!-- https://mvnrepository.com/artifact/org.apache.shardingsphere/sharding-jdbc-spring-boot-starter -->
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-spring-boot-starter</artifactId>
<version>4.1.1</version>
</dependency>
application.yml配置基本如下:
# 配置分库分表
spring:
main:
# 允许定义相同的bean对象去覆盖原有的
allow-bean-definition-overriding: true
shardingsphere:
props:
sql:
# 打开sql输出日志
show: true
datasource:
names: ds1
ds1:
# type: com.zaxxer.hikari.HikariDataSource
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?useUnicode=true&serverTimezone=UTC
username: root
password: 123456
sharding:
# 未配置分片规则的表将通过默认数据源定位
default-data-source-name: ds1
tables:
t_user:
actual-data-nodes: ds1.t_user_$->{0..1}
table-strategy:
standard:
sharding-column: user_name
precise-algorithm-class-name: com.test.core.infrastructure.shard.HashShardingAlgorithm
binding-tables:
- t_user
default-database-strategy:
inline:
sharding-column: id
algorithm-expression: ds$->{1}
使用自定义的分片算法:
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;
import java.util.Collection;
/**
* @Description 非自增字段通过hash分片
* @Author jack
* @Date 2024/9/3 14:25
*/
public class HashShardingAlgorithm implements PreciseShardingAlgorithm<String> {
@Override
public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<String> shardingValue) {
// 计算用户名的哈希值,并根据哈希值选择分片
String columnValue = shardingValue.getValue();
int hashCode = columnValue.hashCode();
int index = Math.abs(hashCode) % availableTargetNames.size();
// 返回实际的目标表名
return availableTargetNames.stream().skip(index).findFirst().orElse(null);
}
}
- 在使用5.x的时候,maven仓库中的最新版本是5.2.1,使用的依赖:
<!-- https://mvnrepository.com/artifact/org.apache.shardingsphere/shardingsphere-jdbc-core-spring-boot-starter -->
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>shardingsphere-jdbc-core-spring-boot-starter</artifactId>
<version>5.2.0</version>
</dependency>