maven配置
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-spring-boot-starter</artifactId>
<version>4.0.1</version>
</dependency>
application.yml配置
spring:
shardingsphere:
props:
sql:
show: true
datasource:
names: xxxx # 真实数据源名称,多个数据源用逗号区分
database1: #对应上面names
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://ip:port/database?jdbcCompliantTruncation=false&characterSetResults=utf8&autoReconnect=true&failOverReadOnly=false&useSSL=false
userName: xxx
password: xxx
sharding:
binding-tables: table_
tables:
table_:
actual-data-nodes: database.table_$->{0..99} #100张表
table-starategy:
standard:
sharding-column: xxx #分表字段
precise-algorithm-class-name: com.xxx.xxx.xx.MySpringPhysicalNamingStrategy
参考:
- https://shardingsphere.apache.org/document/current/cn/user-manual/shardingsphere-jdbc/spring-boot-starter/data-source/
- https://shardingsphere.apache.org/document/current/cn/user-manual/shardingsphere-jdbc/spring-boot-starter/rules/sharding/
MySpringPhysicalNamingStrategy分表逻辑
public class MySpringPhysicalNamingStrategy implements PreciseShardingAlgorithm<String> {
@Override
public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<String> preciseShardingValue) {
CRC32 crc32 = new CRC32();
crc32.update(preciseShardingValue.getValue().getBytes());
String tableName = "table_" + crc32.getValue() % availableTargetNames.size();
if (availableTargetNames.contains(tableName)) {
return tableName;
}
return null;
}
}