随机批号,随机UUID生成函数PHP
/**
* 生成 uuid v4
* @return string
*/
public static function uuidv4()
{
try {
$data = random_bytes(16);
} catch (\Exception $e) {
AppHelper::systemLog($e);
// 兜底:固定前缀+mt_rand,保持和uuid一样格式
return sprintf('00000000-%04x-%04x-%04x-%08x%04x',
mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
mt_rand(0, 0xffffffff),
mt_rand(0, 0xffff)
);
}
$data[6] = chr(ord($data[6]) & 0x0f | 0x40);
$data[8] = chr(ord($data[8]) & 0x3f | 0x80);
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}
/**
* 生成随机的批次码
* @param $prefix
* @param $mode
* @return string
*/
public static function randomBatchCode($prefix = '', $mode = 1)
{
// UUID v4,标准唯一,无小数点
$prefix = $prefix != '' ? $prefix . '-' : '';
$str = $prefix . self::uuidv4();
if ($mode != 1) {
return str_replace('-', '', $str);
}
return $str;
}
/**
* 纯数字订单号: 雪花算法,时钟回拨时自动降级到时间随机方案兜底
* @param string $prefix 订单号前缀
* @param int $machineId 机器编号 0~31
* @return string
*/
public static function createOrderSn($prefix='', int $machineId = 1): string
{
static $lastTimestamp = 0;
static $sequence = 0;
$epoch = 1609459200000;
$timestamp = (int)(microtime(true) * 1000);
// 时钟回拨,直接降级简易方案,不报错
if ($timestamp < $lastTimestamp) {
return self::createOrderSnSimple($prefix);
}
if ($timestamp === $lastTimestamp) {
$sequence = ($sequence + 1) & 4095;
if ($sequence === 0) {
usleep(1000);
$timestamp = (int)(microtime(true) * 1000);
// 再次判断回拨兜底
if ($timestamp < $lastTimestamp) {
return self::createOrderSnSimple($prefix);
}
}
} else {
$sequence = 0;
}
$lastTimestamp = $timestamp;
$timePart = $timestamp - $epoch;
$snowflake = ($timePart << 22) | ($machineId << 17) | $sequence;
$snowflake = (string)$snowflake;
return $prefix . $snowflake;
}
/**
* 纯数字订单号生成函数(兜底方案):毫秒时间 + 6位随机,纯数字,永远不会抛异常
* @param string $prefix 订单号前缀
* @return string
*/
public static function createOrderSnSimple($prefix = ''): string
{
$ms = (string)(microtime(true) * 1000);
$ms = explode('.', $ms)[0];
try {
$rand_number = random_int(0, 999999);
} catch (\Exception $e) {
//AppHelper::systemLog($e);
$rand_number = mt_rand(0, 999999);
}
$rand = str_pad($rand_number, 6, '0', STR_PAD_LEFT);
return $prefix . $ms . $rand;
}版权属于:Joyber
本文链接:https://blog.qqvbc.com/default/UUID-PHP.html
转载时须注明出处及本声明