PHP產生唯一ID之SnowFlake演算法詳解

來源:互聯網
上載者:User
snowflake演算法是個啥?首先我來提出個問題,怎麼在分布式系統中產生唯一性id並保持該id大致自增?在twitter中這是最重要的業務情境,於是twitter推出了一種snowflake演算法。

前言:最近需要做一套CMS系統,由於功能比較單一,而且要求靈活,所以放棄了WP這樣的成熟系統,自己做一套相對簡單一點的。文章的詳情頁URL想要做成url偽靜態格式即xxx.html 其中xxx考慮過直接用自增主鍵,但是感覺這樣有點暴露文章數量,有同學說可以把初始值設高一點,可是還是可以通過ID差算出一段時間內的文章數量,所以需要一種可以產生唯一ID的演算法。

考慮過的方法有

  1. 直接用時間戳記,或者以此衍生的一系列方法

  2. Mysql內建的uuid

以上兩種方法都可以查到就不多做解釋了

最終選擇了Twitter的SnowFlake演算法

這個演算法的好處很簡單可以在每秒產生約400W個不同的16位元字ID(10進位)

原理很簡單

ID由64bit組成

其中 第一個bit空缺

41bit用於存放毫秒級時間戳記

10bit用於存放機器id

12bit用於存放自增ID

除了最高位bit標記為不可用以外,其餘三組bit佔位均可浮動,看具體的業務需求而定。預設情況下41bit的時間戳記可以支援該演算法使用到2082年,10bit的工作機器id可以支援1023台機器,序號支援1毫秒產生4095個自增序列id。
下面是PHP源碼

<?phpnamespace App\Services;abstract class Particle {  const EPOCH = 1479533469598;  const max12bit = 4095;  const max41bit = 1099511627775;  static $machineId = null;  public static function machineId($mId = 0) {    self::$machineId = $mId;  }  public static function generateParticle() {    /*    * Time - 42 bits    */    $time = floor(microtime(true) * 1000);    /*    * Substract custom epoch from current time    */    $time -= self::EPOCH;    /*    * Create a base and add time to it    */    $base = decbin(self::max41bit + $time);    /*    * Configured machine id - 10 bits - up to 1024 machines    */    if(!self::$machineId) {      $machineid = self::$machineId;    } else {      $machineid = str_pad(decbin(self::$machineId), 10, "0", STR_PAD_LEFT);    }        /*    * sequence number - 12 bits - up to 4096 random numbers per machine    */    $random = str_pad(decbin(mt_rand(0, self::max12bit)), 12, "0", STR_PAD_LEFT);    /*    * Pack    */    $base = $base.$machineid.$random;    /*    * Return unique time id no    */    return bindec($base);  }  public static function timeFromParticle($particle) {    /*    * Return time    */    return bindec(substr(decbin($particle),0,41)) - self::max41bit + self::EPOCH;  }}?>

調用方法如下

Particle::generateParticle($machineId);//產生IDParticle::timeFromParticle($particle);//反向計算時間戳記

這裡我做了改良 如果機器ID傳0 就會去掉這10bit 因為有些時候我們可能用不到這麼多ID

以上就是本文的全部內容,希望對大家的學習有所協助。


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.