MySQL分库分表是一种数据库优化策略,用于解决单点数据库在高并发、大数据量情况下的性能瓶颈问题。分库是将一个数据库拆分为多个数据库,分表是将一个大表拆分为多个小表,通常基于某种规则(如哈希、范围等)进行拆分。
适用于数据量巨大、访问量高、业务复杂的应用系统,如电商、社交网络等。
// 引入ShardingSphere依赖
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-core</artifactId>
<version>4.1.1</version>
</dependency>
// 配置ShardingSphere分片规则
Map<String, DataSource> dataSourceMap = new HashMap<>();
dataSourceMap.put("ds0", createDataSource("jdbc:mysql://localhost:3306/db0"));
dataSourceMap.put("ds1", createDataSource("jdbc:mysql://localhost:3306/db1"));
TableRuleConfiguration tableRuleConfig = new TableRuleConfiguration("t_order", "ds${0..1}.t_order${0..1}");
tableRuleConfig.setDatabaseShardingStrategyConfig(new InlineShardingStrategyConfiguration("user_id", "ds${user_id % 2}"));
tableRuleConfig.setTableShardingStrategyConfig(new InlineShardingStrategyConfiguration("order_id", "t_order${order_id % 2}"));
ShardingRuleConfiguration shardingRuleConfig = new ShardingRuleConfiguration();
shardingRuleConfig.getTableRuleConfigs().add(tableRuleConfig);
shardingRuleConfig.setDefaultDatabaseShardingStrategyConfig(new InlineShardingStrategyConfiguration("user_id", "ds${user_id % 2}"));
shardingRuleConfig.setDefaultTableShardingStrategyConfig(new InlineShardingStrategyConfiguration("order_id", "t_order${order_id % 2}"));
DataSource dataSource = ShardingDataSourceFactory.createDataSource(dataSourceMap, shardingRuleConfig, new Properties());
// 使用分片数据源进行数据库操作
try (Connection conn = dataSource.getConnection();
PreparedStatement ps = conn.prepareStatement("SELECT * FROM t_order WHERE order_id = ?")) {
ps.setLong(1, 123456L);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
// 处理查询结果
}
}
}
领取专属 10元无门槛券
手把手带您无忧上云