需求背景:已经有几千万的注册用户数据,而我们数据库一张表上限大约是5000W条数据,而我们往往也不能真的全部占用,这就要必须对用户数据分库分表了。分表分为水平拆分和垂直拆分,这里我写的就是一个关于水平拆分的demo。
实验:
工具和环境:jdk1.8, idea, sharding-jdbc, mybatis, postgresql(数据库,因为目前公司用的这个数据库,所以拿这个做的),springboot,maven
思路:对用户表(t_user_info)进行拆分。
1.我创建2张表t_user_info_0和t_user_info_1,这2个表就是t_user_info将拆分成的表。
2.我们插入数据时如何保证每条数据进入这2个表的机率时平均的呢?我们在表中加入一个字段role_id来路由一条插入数据将进入哪张表,我采取的方法是,创建一个自增序列表seq_t_user_role_id,每次插入一条数据的时候先去获取序列号,然后在将获取的值与我要分的表的数量取余(seq_id%table_count),而得到的值就是我们要插入表名的后缀。例如1%2=1,所以是表t_user_info_1,2%2=0 对应的表t_user_info_0.
实战:
1. 创建分表和序列

2.用idea快速搭建一个可运行的springboot的web项目,项目名demo(取名障碍症,请原谅),下面是我的包结构。

3.加入数据库等依赖包。

4.配置sharding-jdbc(具体sharding配置信息可以看sharding的官网):

因为sharding-jdbc-spring-boot-starter包在启动时会自动帮我们创建datasource:

配置sqlSessionFactory:

然后贴上超级简单的实现代码:




最后贴上项目源码地址:https://gitee.com/yijy/partitiontabledemo。
请各位大佬轻喷,欢迎留言交流!
网友评论