Forced Routing Overview
Basic Introduction
ShardingSphere’s Hint mechanism is used when the sharding condition does not exist in the SQL itself, but is provided by external business logic. HintManager is the key component, and it uses ThreadLocal to keep routing context isolated per thread.
Typical use cases:
- Cross-database transactions that must route multiple operations to the same node
- Special queries that need to target a specific shard
- System maintenance scenarios that direct operations to a chosen node
- Complex queries where the sharding key is not present in the SQL
try (HintManager hintManager = HintManager.getInstance()) {
hintManager.addDatabaseShardingValue("order", 1);
hintManager.addTableShardingValue("order", 1);
orderRepository.queryOrders();
}
Usage Scenarios
Data Sharding Operations
Use Hint routing when the sharding key is not directly reflected in SQL or table structure, but is calculated dynamically by business logic:
- Composite sharding keys
- Derived sharding keys
- External system dependencies
Read/Write Splitting Operations
Force routing to the primary database in scenarios such as:
- Financial transaction records, inventory deduction, and flash-sale orders
- Queries inside transactions to avoid stale reads
- Write-then-read workflows that require strong consistency
Usage Process
1. Implement HintShardingAlgorithm
public class MyHintShardingAlgorithm implements HintShardingAlgorithm<Integer> {
@Override
public Collection<String> doSharding(Collection<String> availableTargetNames,
HintShardingValue<Integer> shardingValue) {
return availableTargetNames;
}
}
2. Configure the Hint Strategy
spring.shardingsphere.sharding.tables.b_order.database-strategy.hint.algorithm-class-name=com.lagou.hint.MyHintShardingAlgorithm
spring.shardingsphere.sharding.tables.b_order.actual-data-nodes=ds$->{0..1}.b_order$->{0..1}
3. Use HintManager in Code
try (HintManager hintManager = HintManager.getInstance()) {
hintManager.addDatabaseShardingValue("b_order", 1);
hintManager.addTableShardingValue("b_order", 1);
List<Order> list = orderRepository.findAll();
}
4. Force Primary Routing for Read/Write Splitting
try (HintManager hintManager = HintManager.getInstance()) {
hintManager.setMasterRouteOnly();
// Execute SQL queries that require fresh data.
}