JAVA生成短8位UUID的實例講解
短8位UUID思想其實借鑒微博短域名的生成方式,但是其重復(fù)概率過高,而且每次生成4個,需要隨即選取一個。
本算法利用62個可打印字符,通過隨機生成32位UUID,由于UUID都為十六進制,所以將UUID分成8組,每4個為一組,然后通過模62操作,結(jié)果作為索引取出字符,
這樣重復(fù)率大大降低。
經(jīng)測試,在生成一千萬個數(shù)據(jù)也沒有出現(xiàn)重復(fù),完全滿足大部分需求。代碼貼出來供大家參考。
public static String[] chars = new String[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' }; public static String generateShortUuid() { StringBuffer shortBuffer = new StringBuffer(); String uuid = UUID.randomUUID().toString().replace('-', ''); for (int i = 0; i < 8; i++) { String str = uuid.substring(i * 4, i * 4 + 4); int x = Integer.parseInt(str, 16); shortBuffer.append(chars[x % 0x3E]); } return shortBuffer.toString(); }
補充:生成 8 / 16 / 32 位的UUID
我就廢話不多說了,大家還是直接看實例吧~
import java.util.UUID; public class TestUUID { // 得到16位的UUID-(數(shù)字)public static String getUUID_16() {int machineId = 1;// 最大支持1-9個集群機器部署 int hashCodeV = UUID.randomUUID().toString().hashCode();if (hashCodeV < 0) {// 有可能是負數(shù)hashCodeV = -hashCodeV;}String string = machineId + String.format('%015d', hashCodeV);return string;} // 得到32位的UUID-(數(shù)字)public static String getUUID_32() {return UUID.randomUUID().toString().replace('-', '').toLowerCase();} //得到8位的UUID-(碼)public static String[] chars = new String[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n','o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8','9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T','U', 'V', 'W', 'X', 'Y', 'Z' }; public static String getUUID_8() {StringBuffer shortBuffer = new StringBuffer();String uuid = UUID.randomUUID().toString().replace('-', '');for (int i = 0; i < 8; i++) {String str = uuid.substring(i * 4, i * 4 + 4);int x = Integer.parseInt(str, 16);shortBuffer.append(chars[x % 0x3E]);}return shortBuffer.toString(); } public static void main(String[] args) { System.out.println(getUUID_8());} }
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。如有錯誤或未考慮完全的地方,望不吝賜教。
相關(guān)文章:
