分库分表策略
根据订单ID分库分表,M库N表,orderId 落到哪张表的算法:
- 表ID = 订单ID后六位 % (库数量 * 每库表数量)
- 库ID = 表ID / 每库表数量
表ID范围 0 到 (M*N-1),库ID范围 0 到 (M-1)
Code:
/**
* MySQL 分库分表策略
*/
public class TableShardingStrategy {
public record ShardingLocation(int dbId, int tableId) {
}
private final int dbNums;
private final int tableNums;
public TableShardingStrategy(int dbNums, int tableNums) {
if (dbNums <= 0) {
throw new IllegalArgumentException("dbNums must > 0");
}
if (tableNums <= 0) {
throw new IllegalArgumentException("tableNums must > 0");
}
this.dbNums = dbNums;
this.tableNums = tableNums;
}
public ShardingLocation getShardingLocation(long primaryId) {
int shardingId = (int) (primaryId % 1000_000);
int tableId = shardingId % (dbNums * tableNums);
int dbId = tableId / tableNums;
return new ShardingLocation(dbId, tableId);
}
}