Sharding-JDBC:单库分表的实现

本文详细介绍了在数据库用户量增长时,如何通过水平拆分来解决大数据量问题。具体步骤包括配置Spring ShardingSphere进行分表,使用inline表达式根据id进行分片,并展示了自定义分表策略的实现。这种方法有助于提高数据库性能和系统稳定性。
摘要由CSDN通过智能技术生成

随着系统用户量的增加,某些业务表的数据会急剧上升,超过1千万以上,这时就要考虑对表进行水平拆分。

表的水平拆分

将一个表拆分成N个表,拆分成多个子表,如user表,拆分user_0,user_1,…user_4
在这里插入图片描述

application.properties


spring.shardingsphere.datasource.names=master
# 数据源
spring.shardingsphere.datasource.master.type=com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.master.driver-class-name=com.mysql.jdbc.Driver
spring.shardingsphere.datasource.master.url=jdbc:mysql://localhost:3306/ds_2?characterEncoding=utf-8
spring.shardingsphere.datasource.master.username=root
spring.shardingsphere.datasource.master.password=

# 分表配置
spring.shardingsphere.sharding.tables.user.actual-data-nodes=master.user_${0..4} #配置分表信息,这边用的inline表达式

#分表策略
# inline 表达式
spring.shardingsphere.sharding.tables.user.table-strategy.inline.sharding-column=id #分表的字段,这边用id分表
spring.shardingsphere.sharding.tables.user.table-strategy.inline.algorithm-expression=user_${id.longValue() % 5} #分表算法行表达式,需符合groovy语法,上面的配置就是用id进行取模分片

#可自定义分表策略
#spring.shardingsphere.sharding.tables.user.table-strategy.standard.sharding-column=id
#spring.shardingsphere.sharding.tables.user.table-strategy.standard.precise-algorithm-class-name=

# 显示SQL
spring.shardingsphere.props.sql.show=true

自定义分表策略类

public class MyPreciseShardingAlgorithm implements PreciseShardingAlgorithm<Long> {

	@Override
	public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Long> shardingValue) {

	    for (String tableName : availableTargetNames) {
			if (tableName.endsWith(shardingValue.getValue() % 4 + "")) {
				return tableName;
			}
		}
		throw new IllegalArgumentException();
	}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值