PHP使用SnowFlake算法生成惟一ID

使用SnowFlake算法生成惟一ID


前言:最近须要作一套CMS系统,因为功能比较单一,并且要求灵活,因此放弃了WP这样的成熟系统,本身作一套相对简单一点的。文章的详情页URL想要作成url伪静态的格式即xxx.html 其中xxx考虑过直接用自增主键,可是感受这样有点暴露文章数量,有同窗说能够把初始值设高一点,但是仍是能够经过ID差算出一段时间内的文章数量,因此须要一种能够生成惟一ID的算法。php

考虑过的方法有html

  • 直接用时间戳,或者以此衍生的一系列方法算法

  • Mysql自带的uuidsql

以上两种方法均可以查到就很少作解释了dom

最终选择了Twitter的SnowFlake算法ui

这个算法的好处很简单能够在每秒产生约400W个不一样的16位数字ID(10进制)url

原理很简单spa

ID由64bit组成code

其中 第一个bit空缺htm

41bit用于存放毫秒级时间戳

10bit用于存放机器id

12bit用于存放自增ID

除了最高位bit标记为不可用之外,其他三组bit占位都可浮动,看具体的业务需求而定。默认状况下41bit的时间戳能够支持该算法使用到2082年,10bit的工做机器id能够支持1023台机器,序列号支持1毫秒产生4095个自增序列id。

下面是PHP源码

<?php
namespace 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);//生成ID
Particle::timeFromParticle($particle);//反向计算时间戳

这里我作了改良 若是机器ID传0 就会去掉这10bit 由于有些时候咱们可能用不到这么多ID

相关文章
相关标签/搜索