六 高级使用案例
1. 数据库分片路由
数据库分片(Sharding)主要是为了解决以下几个问题:
性能瓶颈:单机数据库在数据量达到TB级别时性能急剧下降
存储限制:单机存储容量有限
高并发:单一数据库无法承受极高的并发请求
可用性:避免单点故障
1.1. 首先定义分片核心代码
public class ShardingJdbcTemplate {
private final Map<Integer, JdbcTemplate> shards;
public ShardingJdbcTemplate(Map<Integer, DataSource> shardDataSources) {
this.shards = shardDataSources.entrySet().stream()
.collect(Collectors.toMap(
Map.Entry::getKey,
e -> new JdbcTemplate(e.getValue())
))