之前有发过4.x版本的使用教程,这次项目升级了5.x版本,教程实战贴一下
1. 首先是maven依赖的添加
<!-- Sharding-JDBC -->
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>shardingsphere-jdbc-core-spring-boot-starter</artifactId>
<version>5.1.2</version>
</dependency>
2. yaml的配置,只配置一个数据库,单库分表,使用精准自定义分片策略
5.1.2版本增加一个参数props
,将分片策略和全限定类名配置在这个下面。
而且精准分片的接口StandardShardingAlgorithm实现类需要实现的方法也多了两个,getProps和
@Override
public String doSharding(Collection<T> tableNames, PreciseShardingValue<T> preciseShardingValue) {
return null;
}
@Override
public Collection<String> doSharding(Collection<T> collection, RangeShardingValue<T> rangeShardingValue) {
return null;
}
@Override
public String getType() {
return null;
}
// 新增方法,暂不知用处
@Override
public Properties getProps() {
return null;
}
// 新增方法 删除了原init();方法,多了个参数properties
@Override
public void init(Properties properties) {
}
spring:
main:
allow-bean-definition-overriding: true
shardingsphere:
# 是否启用 Sharding
enabled: true
# 打印sql
props:
sql-show: true
datasource:
names: master
master:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/**?useSSL=false&serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8
username: root
password: root
rules:
sharding:
# 表策略配置
tables:
# terminal_heartbeat 是逻辑表
terminal_heartbeat:
actualDataNodes: master.**
tableStrategy:
# 使用标准分片策略
standard:
# 配置分片字段
shardingColumn: terminal_code
# 分片算法名称,不支持大写字母和下划线,否则启动就会报错
shardingAlgorithmName: time-sharding-altorithm
# 分片算法配置
shardingAlgorithms:
# 分片算法名称,不支持大写字母和下划线,否则启动就会报错
time-sharding-altorithm:
# 类型:自定义策略
type: CLASS_BASED
props:
# 分片策略
strategy: standard
# 分片算法类
algorithmClassName: com.****.ShardingAlgorithmA
3. 踩坑合集:
- ShardingJDBC 5.1.0使用druid连接池需要加dbcp依赖
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-dbcp</artifactId>
<version>10.0.16</version>
</dependency>
- 与flyway一起使用时会报错,因为flyway会查询 information_schema.schemata 用户权限和数据库表集合等信息,而ShardingJDBC暂未支持
官方回复5.1.1已支持pr地址:https://github.com/apache/shardingsphere/issues/16234
但是我已尝试还是无效,会报错:org.apache.shardingsphere.infra.exception.SchemaNotExistedException: Schema ‘information_schema’ 不存在。
解决方法:使用Sharding-proxy,或者禁用flyway