Sharding-JDBC 自定义分片算法
- 自定义分片算法
- Sharding提供了以下4种算法接口
- PreciseShardingAlgorithm
- RangeShardingAlgorithm
- HintShardingAlgorithm
- ComplexKeysShardingAlgorithm
- Sharding提供了以下4种算法接口
- 自定义分片算法实例
- 演示自定义PreciseShardingAlgorithm的使用
- 自定义算法概述
- 表分片策略:
- 分片键:order_id
- 分片算法:以order_id为分片键,分片策略为order_id % 2 + 1
- order_id为偶数,插入t_order_1
- order_id为奇数,插入t_order_2
- 编写自定义的实现类:MyPreciseShardingAlgorithm,实现PreciseShardingAlgorithm接口
- 将自定义实现类配置到application.properties
- 测试自定义实现类
- 表分片策略:
- 步骤流程
-
编写自定义的实现类
public class MyPreciseShardingAlgorithm implements PreciseShardingAlgorithm<Long> { private static final Logger LOGGER = LoggerFactory.getLogger(MyPreciseShardingAlgorithm.class); @Override public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Long> shardingValue) { LOGGER.info("collection:" + JacksonUtil.writeValueAsString(availableTargetNames) + ",preciseShardingValue:" + JacksonUtil.writeValueAsString(shardingValue)); //availableTargetNames: t_order_1,t_order_2 //shardingValue: {"logicTableName":"t_order","columnName":"order_id","value":396416249350848512} //collection:["t_order_1","t_order_2"],preciseShardingValue:{"logicTableName":"t_order","columnName":"order_id","value":396416249350848512} //name为两张订单表 t_order_1 和 t_order_2 for (String name : availableTargetNames) { //订单号取模加1 与 订单表t_order_1 和 t_order_2的尾号做比对,如相等,就直接返回t_order_1 或 t_order_2 if (name.endsWith(String.valueOf(shardingValue.getValue() % 2 + 1))) { LOGGER.info("return name: " + name); return name; } } return null; } }
-
配置自定义算法
# 指定 t_order表的分片策略,分片策略包括分片键和分片算法 spring.shardingsphere.sharding.tables.t_order.table-strategy.standard.sharding-column = order_id spring.shardingsphere.sharding.tables.t_order.table-strategy.standard.precise-algorithm-class-name = com.shair.sharding.MyPreciseShardingAlgorithm
-
编写自定义的实现类
@RunWith(SpringRunner.class) @SpringBootTest class ApplicationTests { @Autowired private OrderDao orderDao; @Test public void testInsertOrder() { for (int i = 0; i < 10; i++) { Order order = new Order(); order.setPrice(new BigDecimal((i + 1) * 5)); order.setUserId(1L); order.setStatus("SUCCESS"); orderDao.insert(order); } } }
-
日志
com.shair.sharding.MyPreciseShardingAlgorithm - collection:["t_order_1","t_order_2"],preciseShardingValue:{"logicTableName":"t_order","columnName":"order_id","value":396416249178882048} com.shair.sharding.MyPreciseShardingAlgorithm - return name: t_order_1 ShardingSphere-SQL - Actual SQL: m2 ::: INSERT INTO t_order_1 (price, user_id, status, order_id) VALUES (?, ?, ?, ?) ::: [10, 1, SUCCESS, 396416249178882048]
- 通过日志可以发现:
- order_id为奇数的被插入到 t_order_2表
- order_id为偶数的被插入到 t_order_1表
- 通过日志可以发现:
-