snowflake php无法实现,如何在PHP中使用SnowFlake算法生成唯一ID

如何在PHP中使用SnowFlake算法生成唯一ID

发布时间:2021-03-18 17:30:11

来源:亿速云

阅读:87

作者:Leah

如何在PHP中使用SnowFlake算法生成唯一ID?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

原理很简单

ID由64bit组成

其中 第一个bit空缺

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);//反向计算时间戳

关于如何在PHP中使用SnowFlake算法生成唯一ID问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值