<?php
/**
* 分布式 id 生成类 组成: <毫秒级时间戳+机器id+序列号>
* 默认情况下41bit的时间戳可以支持该算法使用到2082年,10bit的工作机器id可以支持1023台机器,序列号支持1毫秒产生4095个自增序列id
* @author ljs
*/
class IdCreate
{
const EPOCH = 1479533469598; //开始时间,固定一个小于当前时间的毫秒数
const max12bit = 4095;
const max41bit = 1099511627775;
static $machineId = null; // 机器id
static $suffix = 0; // 0bit 未使用
public static function machineId($mId = 0)
{
self::$machineId = $mId;
}
public static function createOnlyId()
{
// 时间戳 42字节
$time = floor(microtime(true) * 1000);
echo "<br />";
echo $time;
echo '=='.strlen($time);
echo "<br />";
//echo $time1 = decbin($time); //测试
//echo '=='.strlen($time1);
//echo "<br />";
// 当前时间 与 开始时间 差值
$time -= self::EPOCH;
// 二进制的 毫秒级时间戳
$base = decbin(self::max41bit + $time);
echo "<br />";
echo $base;
echo '=='.strlen($base);
echo "<br />";
// 机器id 10 字节
if (!self::$machineId) {
$machineid = self::$machineId;
} else {
$machineid = str_pad(decbin(self::$machineId), 10, "0", STR_PAD_LEFT);
}
echo "<br />";
echo $machineid;
echo '=='.strlen($machineid);
echo "<br />";
// 序列数 12字节
$random = str_pad(decbin(mt_rand(0, self::max12bit)), 12, "0", STR_PAD_LEFT);
echo "<br />";
echo $random;
echo '=='.strlen($random);
echo "<br />";
// 拼接
$base = self::$suffix . $base . $machineid . $random;
echo "<br />";
echo $base;
echo '=='.strlen($base);
echo "<br />";
// 转化为 十进制 返回
return bindec($base);
}
}
$machineId = IdCreate::machineId(1);;
$uniq_id = IdCreate::createOnlyId($machineId);
echo $uniq_id;
返回结果:
1555901303743==13
10001000111000111111000001010110000100000==41
0000000001==10
111001010111==12
100010001110001111110000010101100001000000000000001111001010111==63
4931995930648911447
| 留言与评论(共有 0 条评论) |