UUID 简介(PHP为例)
V1 | V2 | V4 | V3 | V5 | |
---|---|---|---|---|---|
长度组成 | 48bit 主机的 Mac 地址60bit 时间戳 (13-14bit 作为时间序列) | 48bit 主机的 Mac 地址40bit 域名/ID28bit 时间戳(6bit 作为时间序列) | 6bit 标记版本122bit 随机数 | 将值与指定的命名空间拼接后,做 hash 运算,再做一些额外的固定变换得到最终的 UUIDV5 区别于 V3 是使用了更不容易碰撞的 hash 算法,前者 sha1,后者 md5。注意值不变的情况下生成的 UUID 相同 | 同前 |
重复率 | 每个节点每秒钟可生成 1630 亿个,也就是说每毫秒 163 个。 | 允许一个节点存在 1 万亿个 域名/ID 对象,每个对象每 7 秒产生一个 UUID。 | 每秒生成 10 亿个,大约需要 85 年才有重复的可能,所以在正常应用情形下这种碰撞概率可以忽略。 | — | — |
选择 | 有暴露MAC地址的危险,需要反向解析主机 Mac 地址。 | 一般不会用到 | 首选最简单实用的版本 | 需要根据特定的值生成,而且在值不变的情况下生成的 UUID 不变。 | 同前 |
/**
* create v1uuid
* @author doubleam
* @param string $prefix ps
* @param int $median 随机位个数
* @return string
*/
function create_v1uuid($prefix = "uuid-v1: ", $median = 3) {
$randArr = ['8', '9', 'a', 'b'];
$ip = get_ip() ?? 'ip1.ip2.ip3.ip4';
$ipUniqid = uniqid(base_convert(implode('', explode('.', $ip)), 10, 16));
$randNum = md5(uniqid(mt_rand()));
$mt = microtime(); //unix时间戳
list($msc, $ts) = explode(" ", $mt);
$mscStr = uniqid(ltrim($msc, "0."));
$tsStr = dechex($ts);
$uuid = $tsStr . '-'; //时间戳精确到秒
$uuid .= substr($mscStr, 0, 4) . '-';
$uuid .= '1' . substr($mscStr, 4, 3) . '-';
$uuid .= $randArr[mt_rand(0, 3)] . substr($ipUniqid, 0, 3) . '-';
$uuid .= substr($ipUniqid, 4, 9);
$uuid .= substr($randNum, 0, $median);
return $prefix . $uuid;
}
$uuid = "select uuid() as uuid";
echo create_v1uuid();
echo "<br/>uuid-v1: " . mysqli_fetch_assoc(mysqli_query($hxb_db, $uuid))['uuid'];
mysqli_close($hxb_db);
/**
* 获取ip地址
* @return String ip地址
*/
function get_ip() {
if (!empty(filter_input(INPUT_SERVER, 'HTTP_CLIENT_IP'))) {
return filter_input(INPUT_SERVER, 'HTTP_CLIENT_IP');
} elseif (!empty(filter_input(INPUT_SERVER, 'HTTP_X_FORWARDED_FOR'))) {
return filter_input(INPUT_SERVER, 'HTTP_X_FORWARDED_FOR');
} else {
return filter_input(INPUT_SERVER, 'REMOTE_ADDR');
}
}
/**
* create v4uuid
* @author doubleam
* @param string $prefix ps
* @return string
*/
function create_v4uuid($prefix = "uuid-v4: ") {
$randArr = ['8', '9', 'a', 'b'];
$str = md5(uniqid(mt_rand(), true));
$uuid = substr($str, 0, 8) . '-';
$uuid .= substr($str, 8, 4) . '-';
$uuid .= '4' . substr($str, 12, 3) . '-';
$uuid .= $randArr[mt_rand(0, 3)] . substr($str, 15, 3) . '-';
$uuid .= substr($str, 19, 12);
return $prefix . $uuid;
}
echo create_v4uuid();
echo "<br/>uuid-v4: " . trim(com_create_guid(), '{}');