发布于: 2022-06-01 14:24:18
/**
 * 雪花算法类
 * @package App\Helper
 */
class SnowFlake
{
    const EPOCH = 1653634710598; //软件时间,精确到毫秒的unix时间戳
    const max12bit = 4095;  //12 bit 可以代表的最大正整数是 2 ^ 12 - 1 = 4096,也就是说可以用这个 12 bit 代表的数字来区分同一个毫秒内的 4096 个不同的 id。也就是同一毫秒内同一台机器所生成的最大ID数量为4096
    const max41bit = 1099511627775; //2的40次方-1 表示的是时间戳。

    static $machineId = 0;//10bit 记录工作机器 id,代表的是这个服务最多可以部署在 2^10 台机器上,也就是 1024 台机器

    //赋值机器id
    public static function machineId($mId = 1) {
        self::$machineId = $mId;
    }

    //生成雪花id
    public static function generateParticle() {

        //精确到毫秒的时间戳
        $time = floor(microtime(true) * 1000);
        //当前时间减去软件上线时间
        $time -= self::EPOCH;

        //雪花id 41位时间戳
        $base = decbin(self::max41bit + $time);

        if(empty(self::$machineId)){
            self::$machineId=0;
        }

        //服务器编号
        $machineId = str_pad(decbin(self::$machineId), 10, "0", STR_PAD_LEFT);

        //每台服务器同一毫秒可生成的id
        $random = str_pad(decbin(mt_rand(0, self::max12bit)), 12, "0", STR_PAD_LEFT);

        //构建二进制雪花id
        $base = $base.$machineId.$random;

        //返回雪花id
        return bindec($base);
    }

    //雪花id转换为精确到毫秒的time
    public static function timeFromParticle($particle) {
        return bindec(substr(decbin($particle),0,41)) - self::max41bit + self::EPOCH;
    }
}


延伸阅读
    发表评论