what
UUID含义是通用唯一识别码 (Universally Unique Identifier),这 是一个软件建构的标准,也是被开源软件基金会 (Open Software Foundation, OSF) 的组织应用在分布式计算环境(Distributed Computing Environment, DCE) 领域的一部分。
UUID 的目的是让分布式系统中的所有元素,都能有唯一的辨识资讯,而不需要透过中央控制端来做辨识资讯的指定。如此一来,每个人都可以建立不与其它人冲突的 UUID。在这样的情况下,就不需考虑数据库建立时的名称重复问题。目前最广泛应用的 UUID,即是微软的 Microsoft's Globally Unique Identifiers (GUIDs),而其他重要的应用,则有 Linux ext2/ext3 档案系统、LUKS 加密分割区、GNOME、KDE、Mac OS X 等等。
UUID格式规范
这128bits的结构如下所示:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| time_low |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| time_mid | time_hi_and_version |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|clk_seq_hi_res | clk_seq_low | node (0-1) |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| node (2-5) |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
time-low = 4hexOctet
time-mid = 2hexOctet
time-high-and-version = 2hexOctet // MOST IMPORTANT !
clock-seq-and-reserved = hexOctet
clock-seq-low = hexOctet
node = 6hexOctet
hexOctet = hexDigit hexDigit
hexDigit =
"0" / "1" / "2" / "3" / "4" / "5" / "6" / "7" / "8" / "9" /
"a" / "b" / "c" / "d" / "e" / "f" /
"A" / "B" / "C" / "D" / "E" / "F"
how
java uuid
UUID是1.5中新增的一个类,在java.util下,用它可以产生一个号称全球唯一的ID
源码
public final classUUIDimplementsjava.io.Serializable, Comparable
/**
* Static factory to retrieve a type 4 (pseudo randomly generated) UUID.
* The {@codeUUID} is generated using a cryptographically strong pseudo
* random number generator.
*@returnA randomly generated {@codeUUID}
*/
public staticUUID randomUUID() {
SecureRandom ng = Holder.numberGenerator;
byte[] randomBytes =new byte[16];
ng.nextBytes(randomBytes);
randomBytes[6] &=0x0f;/* clear version */
randomBytes[6] |=0x40;/* set to version 4 */
randomBytes[8] &=0x3f;/* clear variant */
randomBytes[8] |=0x80;/* set to IETF variant */
return newUUID(randomBytes);
}
js
可以自己实现算法、引用npm uuid或者第三方js
下面是js算法
function generateUUID(){
var d = new Date().getTime();
var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = (d + Math.random()*16)%16 | 0;
d = Math.floor(d/16);
return (c=='x' ? r : (r&0x7|0x8)).toString(16);
});
return uuid;
};
也可以用npm直接引用
详细参考 https://www.npmjs.com/package/uuid
其他版本的uuid
PHP - uniqid()http://php.net/manual/en/function.uniqid.php#94959
Mysql - UUID()http://dev.mysql.com/doc/refman/5.1/en/miscellaneous-functions.html#function_uuid
参考文献:
java产生随机uuid的性能
npm uuid