<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          使用雪花id或uuid作為Mysql主鍵,被老板懟了一頓!

          共 8566字,需瀏覽 18分鐘

           ·

          2022-03-09 22:13

          點(diǎn)擊關(guān)注公眾號(hào),回復(fù)“2T”獲取2TB學(xué)習(xí)資源!

          互聯(lián)網(wǎng)架構(gòu)師后臺(tái)回復(fù) 2T 有特別禮包

          上一篇:再說一次,別去外包!

          作者:老男孩的架構(gòu)路
          鏈接:https://www.jianshu.com/p/b0602394869e

          一:mysql和程序?qū)嵗?/span>

          1.1:要說明這個(gè)問題,我們首先來建立三張表,分別是user_auto_key,user_uuid,user_random_key,分別表示自動(dòng)增長的主鍵,uuid作為主鍵,隨機(jī)key作為主鍵,其它我們完全保持不變.根據(jù)控制變量法,我們只把每個(gè)表的主鍵使用不同的策略生成,而其他的字段完全一樣,然后測試一下表的插入速度和查詢速度:
          注:這里的隨機(jī)key其實(shí)是指用雪花算法算出來的前后不連續(xù)不重復(fù)無規(guī)律的id:一串18位長度的long值
          id自動(dòng)生成表:

          用戶uuid表

          隨機(jī)主鍵表:

          1.2:光有理論不行,直接上程序,使用spring的jdbcTemplate來實(shí)現(xiàn)增查測試:

          技術(shù)框架:springboot+jdbcTemplate+junit+hutool,程序的原理就是連接自己的測試數(shù)據(jù)庫,然后在相同的環(huán)境下寫入同等數(shù)量的數(shù)據(jù),來分析一下insert插入的時(shí)間來進(jìn)行綜合其效率,另外搜索公眾號(hào)互聯(lián)網(wǎng)架構(gòu)師后臺(tái)回復(fù)“2T”,獲取一份驚喜禮包。為了做到最真實(shí)的效果,所有的數(shù)據(jù)采用隨機(jī)生成,比如名字、郵箱、地址都是隨機(jī)生成,程序已上傳自gitee,地址在文底。
          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("執(zhí)行sql時(shí)間消耗");

                  /**
                   * auto_increment key任務(wù)
                   */

                  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("自動(dòng)生成key表任務(wù)開始");
                  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消耗的時(shí)間:" + (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表任務(wù)開始");
                  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消耗的時(shí)間:" + (over - begin));

                  stopwatch.stop();

                  /**
                   * 隨機(jī)的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("隨機(jī)的long值key表任務(wù)開始");
                  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("隨機(jī)key任務(wù)消耗時(shí)間:" + (end - start));
                  stopwatch.stop();

                  String result = stopwatch.prettyPrint();
                  System.out.println(result);
              }

          1.3:程序?qū)懭虢Y(jié)果

          user_key_auto寫入結(jié)果:

          user_random_key寫入結(jié)果:

          user_uuid表寫入結(jié)果:

          1.4:效率測試結(jié)果

          在已有數(shù)據(jù)量為130W的時(shí)候:我們再來測試一下插入10w數(shù)據(jù),看看會(huì)有什么結(jié)果:

          可以看出在數(shù)據(jù)量100W左右的時(shí)候,uuid的插入效率墊底,并且在后序增加了130W的數(shù)據(jù),uudi的時(shí)間又直線下降。時(shí)間占用量總體可以打出的效率排名為:auto_key>random_key>uuid,uuid的效率最低,在數(shù)據(jù)量較大的情況下,效率直線下滑。那么為什么會(huì)出現(xiàn)這樣的現(xiàn)象呢?帶著疑問,我們來探討一下這個(gè)問題:


          二:使用uuid和自增id的索引結(jié)構(gòu)對(duì)比

          2.1:使用自增id的內(nèi)部結(jié)構(gòu)

          自增的主鍵的值是順序的,所以Innodb把每一條記錄都存儲(chǔ)在一條記錄的后面。當(dāng)達(dá)到頁面的最大填充因子時(shí)候(innodb默認(rèn)的最大填充因子是頁大小的15/16,會(huì)留出1/16的空間留作以后的 修改):
          ①下一條記錄就會(huì)寫入新的頁中,一旦數(shù)據(jù)按照這種順序的方式加載,主鍵頁就會(huì)近乎于順序的記錄填滿,提升了頁面的最大填充率,不會(huì)有頁的浪費(fèi)
          ②新插入的行一定會(huì)在原有的最大數(shù)據(jù)行下一行,mysql定位和尋址很快,不會(huì)為計(jì)算新行的位置而做出額外的消耗
          ③減少了頁分裂和碎片的產(chǎn)生
          另外,關(guān)注公眾號(hào)互聯(lián)網(wǎng)架構(gòu)師,在后臺(tái)回復(fù):面試,可以獲取我整理的 Java 多線程系列教程,非常齊全。

          2.2:使用uuid的索引內(nèi)部結(jié)構(gòu)

          因?yàn)閡uid相對(duì)順序的自增id來說是毫無規(guī)律可言的,新行的值不一定要比之前的主鍵的值要大,所以innodb無法做到總是把新行插入到索引的最后,而是需要為新行尋找新的合適的位置從而來分配新的空間。另外搜索公眾號(hào)互聯(lián)網(wǎng)架構(gòu)師后臺(tái)回復(fù)“2T”,獲取一份驚喜禮包這個(gè)過程需要做很多額外的操作,數(shù)據(jù)的毫無順序會(huì)導(dǎo)致數(shù)據(jù)分布散亂,將會(huì)導(dǎo)致以下的問題:
          :寫入的目標(biāo)頁很可能已經(jīng)刷新到磁盤上并且從緩存上移除,或者還沒有被加載到緩存中,innodb在插入之前不得不先找到并從磁盤讀取目標(biāo)頁到內(nèi)存中,這將導(dǎo)致大量的隨機(jī)IO
          :因?yàn)閷懭胧莵y序的,innodb不得不頻繁的做頁分裂操作,以便為新的行分配空間,頁分裂導(dǎo)致移動(dòng)大量的數(shù)據(jù),一次插入最少需要修改三個(gè)頁以上
          :由于頻繁的頁分裂,頁會(huì)變得稀疏并被不規(guī)則的填充,最終會(huì)導(dǎo)致數(shù)據(jù)會(huì)有碎片
          在把隨機(jī)值(uuid和雪花id)載入到聚簇索引(innodb默認(rèn)的索引類型)以后,有時(shí)候會(huì)需要做一次OPTIMEIZE TABLE來重建表并優(yōu)化頁的填充,這將又需要一定的時(shí)間消耗。
          結(jié)論:使用innodb應(yīng)該盡可能的按主鍵的自增順序插入,并且盡可能使用單調(diào)的增加的聚簇鍵的值來插入新行

          2.3:使用自增id的缺點(diǎn)

          那么使用自增的id就完全沒有壞處了嗎?并不是,自增id也會(huì)存在以下幾點(diǎn)問題:
          ①:別人一旦爬取你的數(shù)據(jù)庫,就可以根據(jù)數(shù)據(jù)庫的自增id獲取到你的業(yè)務(wù)增長信息,很容易分析出你的經(jīng)營情況
          ②:對(duì)于高并發(fā)的負(fù)載,innodb在按主鍵進(jìn)行插入的時(shí)候會(huì)造成明顯的鎖爭用,主鍵的上界會(huì)成為爭搶的熱點(diǎn),因?yàn)樗械牟迦攵及l(fā)生在這里,并發(fā)插入會(huì)導(dǎo)致間隙鎖競爭
          ③:Auto_Increment鎖機(jī)制會(huì)造成自增鎖的搶奪,有一定的性能損失

          附:Auto_increment的鎖爭搶問題,如果要改善需要調(diào)優(yōu)innodb_autoinc_lock_mode的配置

          三:總結(jié)

          本篇博客首先從開篇的提出問題,建表到使用jdbcTemplate去測試不同id的生成策略在大數(shù)據(jù)量的數(shù)據(jù)插入表現(xiàn),然后分析了id的機(jī)制不同在mysql的索引結(jié)構(gòu)以及優(yōu)缺點(diǎn),深入的解釋了為何uuid和隨機(jī)不重復(fù)id在數(shù)據(jù)插入中的性能損耗,詳細(xì)的解釋了這個(gè)問題。在實(shí)際的開發(fā)中還是根據(jù)mysql的官方推薦最好使用自增id,mysql博大精深,內(nèi)部還有很多值得優(yōu)化的點(diǎn)需要我們學(xué)習(xí)。

          -End-


          最后,關(guān)注公眾號(hào)互聯(lián)網(wǎng)架構(gòu)師,在后臺(tái)回復(fù):2T,可以獲取我整理的 Java 系列面試題和答案,非常齊全。


          正文結(jié)束


          推薦閱讀 ↓↓↓

          1.心態(tài)崩了!稅前2萬4,到手1萬4,年終獎(jiǎng)扣稅方式1月1日起施行~

          2.深圳一普通中學(xué)老師工資單曝光,秒殺程序員,網(wǎng)友:敢問是哪個(gè)學(xué)校畢業(yè)的?

          3.從零開始搭建創(chuàng)業(yè)公司后臺(tái)技術(shù)棧

          4.程序員一般可以從什么平臺(tái)接私活?

          5.清華大學(xué):2021 元宇宙研究報(bào)告!

          6.為什么國內(nèi) 996 干不過國外的 955呢?

          7.這封“領(lǐng)導(dǎo)痛批95后下屬”的郵件,句句扎心!

          8.15張圖看懂瞎忙和高效的區(qū)別!

          瀏覽 50
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          評(píng)論
          圖片
          表情
          推薦
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  激情一区二区三区在线 | 99操在线视频 | 精品久久免费一区二区三区 | 91美女精品 | 国产福利精品在线播放 |