雪花算法+时间回溯

<?php

class IdGenerator
{
    const EPOCH = 1479533469598;  // 自定义起始时间
    const max12bit = 4095;  // 随机序列号的最大值
    const max41bit = 1099511627775; // 时间戳的最大值
    const WAIT_TIME_MS = 1000; // 延迟时间(毫秒)

    static $machineId = null;  // 静态变量,用来存储机器ID
    static $lastTimestamp = 0; // 上次生成ID的时间戳
    static $sequence = 0; // 当前时间戳下的序列号

    public static function machineId($mId = 0) {  // 设定机器ID的方法
        self::$machineId = $mId;
    }

    public static function generateParticle() {  // 生成唯一id的方法
        $time = floor(microtime(true) * 1000);  // 获取当前的毫秒级时间戳

        if ($time < self::$lastTimestamp) {
            // 如果时间回溯,等待足够的时间
            usleep((self::$lastTimestamp - $time + self::WAIT_TIME_MS) * 1000);
            $time = floor(microtime(true) * 1000);
        }

        if ($time == self::$lastTimestamp) {
            self::$sequence++;
            if (self::$sequence > self::max12bit) {
                // 当序列号超过最大值时,等待下一毫秒
                $time = self::$lastTimestamp + 1;
                while ($time <= self::$lastTimestamp) {
                    $time = floor(microtime(true) * 1000);
                }
                self::$sequence = 0;
            }
        } else {
            self::$sequence = 0;
        }

        self::$lastTimestamp = $time;

        $time -= self::EPOCH;  // 减去我们设定的起始时间,得到差值
        $base = decbin(self::max41bit + $time);  // 加上时间戳的最大值并转为二进制

        if (self::$machineId !== null) {
            $machineid = str_pad(decbin(self::$machineId), 10, "0", STR_PAD_LEFT);
        } else {
            $machineid = str_pad(decbin(0), 10, "0", STR_PAD_LEFT);
        }

        $random = str_pad(decbin(self::$sequence), 12, "0", STR_PAD_LEFT); // 使用序列号代替随机数

        $base = $base.$machineid.$random; // 三段拼接成一个二进制字符串

        return bindec($base); // 将二进制转为十进制
    }
}

IdGenerator::machineId(1); // 设置机器ID为 1
var_dump(IdGenerator::generateParticle()); // 生成雪花ID

IdGenerator::machineId(3); // 设置机器ID为 3
for ($i = 0; $i <= 10; $i++) {
    var_dump(IdGenerator::generateParticle()); // 生成雪花ID
}
?>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wsy321123

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值