java8的uuid生成方式比較方便俺附,但是速度不夠快
UUID.randomUUID().toString()
我在自己電腦虛擬機(jī)上進(jìn)行測(cè)試4core,8G溪掀,2.5GHZ
虛擬機(jī)事镣,開(kāi)4個(gè)線(xiàn)程,每個(gè)線(xiàn)程創(chuàng)建100萬(wàn)個(gè)uuid揪胃,那么4個(gè)線(xiàn)程全部完成璃哟,統(tǒng)計(jì)速度僅有10w+ ops/sec
為什么要更快的生成速度?
最近要給流計(jì)算場(chǎng)景中的事件添加分布式唯一編碼喊递,如果生成uuid速度太慢随闪,會(huì)成為吞吐的瓶頸
uuid實(shí)際上是有標(biāo)準(zhǔn)的,具體實(shí)現(xiàn)方法也有很多骚勘,格式也有很多種蕴掏,那么我這里跟jdk的uuid格式保持一致
8-4-4-4-12一共36位,每一位是16進(jìn)制字符
分布式唯一
mac地址+ 時(shí)間信息
UUID生成器獲取本機(jī)的mac地址信息调鲸,那么運(yùn)行在同一臺(tái)設(shè)備上的生成器使用相同的mac地址信息
時(shí)間信息則由下面的方式獲取
public static long createTime(final long currentTimeMillis) {
final long timeMillis = currentTimeMillis * 10000L + 122192928000000000L;
final long currNewLastTime = atomicLastTime.get();
if (timeMillis > currNewLastTime) {
atomicLastTime.compareAndSet(currNewLastTime, timeMillis);
}
return atomicLastTime.incrementAndGet();
}
UUID生成辦法
public Appendable toAppendable(final Appendable a) {
Appendable out = a;
if (out == null) {
out = new StringBuilder(36);
}
try {
Hex.append(out, (int) (this.time >> 32)).append('-');
Hex.append(out, (short) (this.time >> 16)).append('-');
Hex.append(out, (short) this.time).append('-');
Hex.append(out, (short) (this.clockSeqAndNode >> 48)).append('-');
Hex.append(out, this.clockSeqAndNode, 12);
} catch (IOException ex) {
}
return out;
}
時(shí)間信息是個(gè)long類(lèi)型,64位挽荡,取高32位作為int類(lèi)型數(shù)字作為UUID的第一個(gè)8位藐石,取低32位的前后16位分別作為short類(lèi)型充當(dāng)UUID后面的2個(gè)4位,這時(shí)候剩下的一個(gè)4位和12位則是跟mac地址有關(guān)
clockSeqAndNode |= Hex.parseLong(macAddress)
clockSeqAndNode同樣是long類(lèi)型定拟,那么取高16位作剩下一個(gè)4位于微,最后的12位則通過(guò)跳步得到
public static Appendable append(final Appendable a, final long in, final int length) {
try {
for (int lim = (length << 2) - 4; lim >= 0; lim -= 4) {
a.append(DIGITS[(byte) (in >> lim) & 0xF]);
}
} catch (IOException ex) {
}
return a;
}
那么根據(jù)上面的原理,我們知道同一個(gè)設(shè)備上面生成的uuid有幾個(gè)特點(diǎn)青自,后面的4+12 = 16位是一致的株依,不變的
前面的8+4+4里面第一個(gè)8位短時(shí)間內(nèi)也是不變的,后面2個(gè)4位是不同的延窜,并且連續(xù)生成的話(huà)恋腕,數(shù)值也是連續(xù)的
01e9e106-eee1-f5b0-b4cc-02426648b365
01e9e106-eee1-f5b1-b4cc-02426648b365
01e9e106-eee1-f5b2-b4cc-02426648b365
01e9e106-eee1-f5b3-b4cc-02426648b365
01e9e106-eee1-f5b4-b4cc-02426648b365
01e9e106-eee1-f5b5-b4cc-02426648b365
01e9e106-eee1-f5b6-b4cc-02426648b365
01e9e106-eee1-f5b7-b4cc-02426648b365
01e9e106-eee1-f5b8-b4cc-02426648b365
01e9e106-eee1-f5b9-b4cc-02426648b365
性能
同樣的測(cè)試辦法,生成速度大概230w+ ops/sec逆瑞,是jdk8 uuid速度的20多倍荠藤,完全可以滿(mǎn)足我的需求了伙单。