在mysql中设计表的时候,mysql官方推荐不要使用uuid或者不连续不重复的雪花id(long形且惟一,单机递增),而是推荐连续自增的主键id,官方的推荐是auto\_increment,那么为何不建议采用uuid,使用uuid究竟有什么坏处?java
本篇博客咱们就来分析这个问题,探讨一下内部的缘由。mysql
本篇博客的目录面试
分别是user\_auto\_key,user\_uuid,user\_random\_key,分别表示自动增加的主键,uuid做为主键,随机key做为主键,其它咱们彻底保持不变.算法
根据控制变量法,咱们只把每一个表的主键使用不一样的策略生成,而其余的字段彻底同样,而后测试一下表的插入速度和查询速度:spring
注:这里的随机key实际上是指用雪花算法算出来的先后不连续不重复无规律的id:一串18位长度的long值
id自动生成表:sql
用户uuid表数据库
随机主键表:后端
技术框架:springboot+jdbcTemplate+junit+hutool,程序的原理就是链接本身的测试数据库,而后在相同的环境下写入同等数量的数据,来分析一下insert插入的时间来进行综合其效率,为了作到最真实的效果,全部的数据采用随机生成,好比名字、邮箱、地址都是随机生成。api
搜索Java知音公众号,回复“后端面试”,送你一份Java面试题宝典缓存
`package com.wyq.mysqldemo;` `import cn.hutool.core.collection.CollectionUtil;` `import com.wyq.mysqldemo.databaseobject.UserKeyAuto;` `import com.wyq.mysqldemo.databaseobject.UserKeyRandom;` `import com.wyq.mysqldemo.databaseobject.UserKeyUUID;` `import com.wyq.mysqldemo.diffkeytest.AutoKeyTableService;` `import com.wyq.mysqldemo.diffkeytest.RandomKeyTableService;` `import com.wyq.mysqldemo.diffkeytest.UUIDKeyTableService;` `import com.wyq.mysqldemo.util.JdbcTemplateService;` `import org.junit.jupiter.api.Test;` `import org.springframework.beans.factory.annotation.Autowired;` `import org.springframework.boot.test.context.SpringBootTest;` `import org.springframework.util.StopWatch;` `import java.util.List;` `@SpringBootTest` `class MysqlDemoApplicationTests {` `@Autowired` `private JdbcTemplateService jdbcTemplateService;` `@Autowired` `private AutoKeyTableService autoKeyTableService;` `@Autowired` `private UUIDKeyTableService uuidKeyTableService;` `@Autowired` `private RandomKeyTableService randomKeyTableService;` `@Test` `void testDBTime() {` `StopWatch stopwatch = new StopWatch("执行sql时间消耗");` `/**` `* auto_increment key任务` `*/` `final String insertSql = "INSERT INTO user_key_auto(user_id,user_name,sex,address,city,email,state) VALUES(?,?,?,?,?,?,?)";` `List<UserKeyAuto> insertData = autoKeyTableService.getInsertData();` `stopwatch.start("自动生成key表任务开始");` `long start1 = System.currentTimeMillis();` `if (CollectionUtil.isNotEmpty(insertData)) {` `boolean insertResult = jdbcTemplateService.insert(insertSql, insertData, false);` `System.out.println(insertResult);` `}` `long end1 = System.currentTimeMillis();` `System.out.println("auto key消耗的时间:" + (end1 - start1));` `stopwatch.stop();` `/**` `* uudID的key` `*/` `final String insertSql2 = "INSERT INTO user_uuid(id,user_id,user_name,sex,address,city,email,state) VALUES(?,?,?,?,?,?,?,?)";` `List<UserKeyUUID> insertData2 = uuidKeyTableService.getInsertData();` `stopwatch.start("UUID的key表任务开始");` `long begin = System.currentTimeMillis();` `if (CollectionUtil.isNotEmpty(insertData)) {` `boolean insertResult = jdbcTemplateService.insert(insertSql2, insertData2, true);` `System.out.println(insertResult);` `}` `long over = System.currentTimeMillis();` `System.out.println("UUID key消耗的时间:" + (over - begin));` `stopwatch.stop();` `/**` `* 随机的long值key` `*/` `final String insertSql3 = "INSERT INTO user_random_key(id,user_id,user_name,sex,address,city,email,state) VALUES(?,?,?,?,?,?,?,?)";` `List<UserKeyRandom> insertData3 = randomKeyTableService.getInsertData();` `stopwatch.start("随机的long值key表任务开始");` `Long start = System.currentTimeMillis();` `if (CollectionUtil.isNotEmpty(insertData)) {` `boolean insertResult = jdbcTemplateService.insert(insertSql3, insertData3, true);` `System.out.println(insertResult);` `}` `Long end = System.currentTimeMillis();` `System.out.println("随机key任务消耗时间:" + (end - start));` `stopwatch.stop();` `String result = stopwatch.prettyPrint();` `System.out.println(result);` `}`
user\_key\_auto写入结果:
user\_random\_key写入结果:
user\_uuid表写入结果:
在已有数据量为130W的时候:咱们再来测试一下插入10w数据,看看会有什么结果:
能够看出在数据量100W左右的时候,uuid的插入效率垫底,而且在后序增长了130W的数据,uudi的时间又直线降低。
时间占用量整体能够打出的效率排名为:auto\_key>random\_key>uuid,uuid的效率最低,在数据量较大的状况下,效率直线下滑。那么为何会出现这样的现象呢?带着疑问,咱们来探讨一下这个问题:
自增的主键的值是顺序的,因此Innodb把每一条记录都存储在一条记录的后面。当达到页面的最大填充因子时候(innodb默认的最大填充因子是页大小的15/16,会留出1/16的空间留做之后的 修改):
①下一条记录就会写入新的页中,一旦数据按照这种顺序的方式加载,主键页就会近乎于顺序的记录填满,提高了页面的最大填充率,不会有页的浪费
②新插入的行必定会在原有的最大数据行下一行,mysql定位和寻址很快,不会为计算新行的位置而作出额外的消耗
③减小了页分裂和碎片的产生
由于uuid相对顺序的自增id来讲是毫无规律可言的,新行的值不必定要比以前的主键的值要大,因此innodb没法作到老是把新行插入到索引的最后,而是须要为新行寻找新的合适的位置从而来分配新的空间。
这个过程须要作不少额外的操做,数据的毫无顺序会致使数据分布散乱,将会致使如下的问题:
①写入的目标页极可能已经刷新到磁盘上而且从缓存上移除,或者尚未被加载到缓存中,innodb在插入以前不得不先找到并从磁盘读取目标页到内存中,这将致使大量的随机IO
②由于写入是乱序的,innodb不得不频繁的作页分裂操做,以便为新的行分配空间,页分裂致使移动大量的数据,一次插入最少须要修改三个页以上
③因为频繁的页分裂,页会变得稀疏并被不规则的填充,最终会致使数据会有碎片
在把随机值(uuid和雪花id)载入到聚簇索引(innodb默认的索引类型)之后,有时候会须要作一次OPTIMEIZE TABLE来重建表并优化页的填充,这将又须要必定的时间消耗。
结论:使用innodb应该尽量的按主键的自增顺序插入,而且尽量使用单调的增长的聚簇键的值来插入新行
搜索Java知音公众号,回复“后端面试”,送你一份Java面试题宝典
那么使用自增的id就彻底没有坏处了吗?并非,自增id也会存在如下几点问题:
①别人一旦爬取你的数据库,就能够根据数据库的自增id获取到你的业务增加信息,很容易分析出你的经营状况
②对于高并发的负载,innodb在按主键进行插入的时候会形成明显的锁争用,主键的上界会成为争抢的热点,由于全部的插入都发生在这里,并发插入会致使间隙锁竞争
③Auto\_Increment锁机制会形成自增锁的抢夺,有必定的性能损失
附:Auto\_increment的锁争抢问题,若是要改善须要调优innodb\_autoinc\_lock\_mode的配置
本篇博客首先从开篇的提出问题,建表到使用jdbcTemplate去测试不一样id的生成策略在大数据量的数据插入表现,而后分析了id的机制不一样在mysql的索引结构以及优缺点,深刻的解释了为什么uuid和随机不重复id在数据插入中的性能损耗,详细的解释了这个问题。
在实际的开发中仍是根据mysql的官方推荐最好使用自增id,mysql博大精深,内部还有不少值得优化的点须要咱们学习。