JAVA生成短8位UUID的實例講解
短8位UUID思想其實借鑒微博短域名的生成方式,但是其重復概率過高,而且每次生成4個,需要隨即選取一個。
本算法利用62個可打印字符,通過隨機生成32位UUID,由于UUID都為十六進制,所以將UUID分成8組,每4個為一組,然后通過模62操作,結果作為索引取出字符,
這樣重復率大大降低。
經測試,在生成一千萬個數據也沒有出現重復,完全滿足大部分需求。代碼貼出來供大家參考。
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-(數字)public static String getUUID_16() {int machineId = 1;// 最大支持1-9個集群機器部署 int hashCodeV = UUID.randomUUID().toString().hashCode();if (hashCodeV < 0) {// 有可能是負數hashCodeV = -hashCodeV;}String string = machineId + String.format('%015d', hashCodeV);return string;} // 得到32位的UUID-(數字)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());} }
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持好吧啦網。如有錯誤或未考慮完全的地方,望不吝賜教。
相關文章:
1. java實現圖形化界面計算器2. IntelliJ Idea2017如何修改緩存文件的路徑3. IntelliJ IDEA設置條件斷點的方法步驟4. IIS Express 取代 ASP.NET Development Server的配置方法5. python flask框架快速入門6. Spring-Richclient 0.1.0 發布7. javascript設計模式 ? 建造者模式原理與應用實例分析8. 淺談SpringMVC jsp前臺獲取參數的方式 EL表達式9. Python使用oslo.vmware管理ESXI虛擬機的示例參考10. Express 框架中使用 EJS 模板引擎并結合 silly-datetime 庫進行日期格式化的實現方法
