JAVA生成八位不重復(fù)隨機數(shù)最快的方法總結(jié)(省時間省空間)
原代碼
private String getCode(){ // 生成一個隨機的8位編碼 String code = StringUtils.getRandom(8); // 獲取緩存中的編碼集合 Set<String> codeSets = redisCache.getCacheSet(Constants.ACT_CODE_KEY); // 如果生成的編碼在緩存集合中已經(jīng)存在,則遞歸調(diào)用getCode方法重新生成編碼 if(codeSets.contains(code)){ return getCode(); } // 如果生成的編碼在緩存集合中不存在,則直接返回該編碼 return code; }
缺點:
1.遞歸調(diào)用可能導(dǎo)致性能問題:在生成編碼的過程中,如果隨機生成的編碼已經(jīng)存在于緩存集合中,那么會通過遞歸調(diào)用getCode()
方法重新生成編碼,直到找到一個不存在于緩存集合中的編碼為止。這種遞歸調(diào)用可能會導(dǎo)致性能問題,特別是當緩存集合中的編碼數(shù)量較大時,遞歸的次數(shù)可能非常多,影響系統(tǒng)的響應(yīng)時間和資源消耗。
2.缺乏生成編碼沖突的處理機制:雖然通過遞歸調(diào)用確保了生成的編碼不會與緩存集合中已有的編碼重復(fù),但并沒有處理編碼沖突的其他情況。如果編碼沖突的概率較高,那么遞歸調(diào)用新代碼的次數(shù)可能會很多,影響系統(tǒng)性能。
新代碼:
import java.util.UUID; private String getCode(){ String code = UUID.randomUUID().toString().substring(0, 8); return code; }
UUID是根據(jù)時間戳和計算機MAC地址等數(shù)據(jù)生成的全局唯一標識符,非常適合作為唯一編碼使用。
使用UUID.randomUUID()來獲取一個UUID對象,然后調(diào)用toString()方法將其轉(zhuǎn)換為String類型。接著,我們通過substring(0, 8)方法截取UUID字符串的前8位作為編碼。
UUID內(nèi)容:
package com.muyuan.common.utils.uuid; //記得更改包名 import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.Random; import java.util.concurrent.ThreadLocalRandom; import com.muyuan.common.exception.UtilException; /** * 提供通用唯一識別碼(universally unique identifier)(UUID)實現(xiàn) * * */ public final class UUID implements java.io.Serializable, Comparable<UUID> { private static final long serialVersionUID = -1185015143654744140L; /** * SecureRandom 的單例 * */ private static class Holder { static final SecureRandom numberGenerator = getSecureRandom(); } /** 此UUID的最高64有效位 */ private final long mostSigBits; /** 此UUID的最低64有效位 */ private final long leastSigBits; /** * 私有構(gòu)造 * * @param data 數(shù)據(jù) */ private UUID(byte[] data) { long msb = 0; long lsb = 0; assert data.length == 16 : "data must be 16 bytes in length"; for (int i = 0; i < 8; i++) { msb = (msb << 8) | (data[i] & 0xff); } for (int i = 8; i < 16; i++) { lsb = (lsb << 8) | (data[i] & 0xff); } this.mostSigBits = msb; this.leastSigBits = lsb; } /** * 使用指定的數(shù)據(jù)構(gòu)造新的 UUID。 * * @param mostSigBits 用于 {@code UUID} 的最高有效 64 位 * @param leastSigBits 用于 {@code UUID} 的最低有效 64 位 */ public UUID(long mostSigBits, long leastSigBits) { this.mostSigBits = mostSigBits; this.leastSigBits = leastSigBits; } /** * 獲取類型 4(偽隨機生成的)UUID 的靜態(tài)工廠。 使用加密的本地線程偽隨機數(shù)生成器生成該 UUID。 * * @return 隨機生成的 {@code UUID} */ public static UUID fastUUID() { return randomUUID(false); } /** * 獲取類型 4(偽隨機生成的)UUID 的靜態(tài)工廠。 使用加密的強偽隨機數(shù)生成器生成該 UUID。 * * @return 隨機生成的 {@code UUID} */ public static UUID randomUUID() { return randomUUID(true); } /** * 獲取類型 4(偽隨機生成的)UUID 的靜態(tài)工廠。 使用加密的強偽隨機數(shù)生成器生成該 UUID。 * * @param isSecure 是否使用{@link SecureRandom}如果是可以獲得更安全的隨機碼,否則可以得到更好的性能 * @return 隨機生成的 {@code UUID} */ public static UUID randomUUID(boolean isSecure) { final Random ng = isSecure ? Holder.numberGenerator : getRandom(); 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 new UUID(randomBytes); } /** * 根據(jù)指定的字節(jié)數(shù)組獲取類型 3(基于名稱的)UUID 的靜態(tài)工廠。 * * @param name 用于構(gòu)造 UUID 的字節(jié)數(shù)組。 * * @return 根據(jù)指定數(shù)組生成的 {@code UUID} */ public static UUID nameUUIDFromBytes(byte[] name) { MessageDigest md; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException nsae) { throw new InternalError("MD5 not supported"); } byte[] md5Bytes = md.digest(name); md5Bytes[6] &= 0x0f; /* clear version */ md5Bytes[6] |= 0x30; /* set to version 3 */ md5Bytes[8] &= 0x3f; /* clear variant */ md5Bytes[8] |= 0x80; /* set to IETF variant */ return new UUID(md5Bytes); } /** * 根據(jù) {@link #toString()} 方法中描述的字符串標準表示形式創(chuàng)建{@code UUID}。 * * @param name 指定 {@code UUID} 字符串 * @return 具有指定值的 {@code UUID} * @throws IllegalArgumentException 如果 name 與 {@link #toString} 中描述的字符串表示形式不符拋出此異常 * */ public static UUID fromString(String name) { String[] components = name.split("-"); if (components.length != 5) { throw new IllegalArgumentException("Invalid UUID string: " + name); } for (int i = 0; i < 5; i++) { components[i] = "0x" + components[i]; } long mostSigBits = Long.decode(components[0]).longValue(); mostSigBits <<= 16; mostSigBits |= Long.decode(components[1]).longValue(); mostSigBits <<= 16; mostSigBits |= Long.decode(components[2]).longValue(); long leastSigBits = Long.decode(components[3]).longValue(); leastSigBits <<= 48; leastSigBits |= Long.decode(components[4]).longValue(); return new UUID(mostSigBits, leastSigBits); } /** * 返回此 UUID 的 128 位值中的最低有效 64 位。 * * @return 此 UUID 的 128 位值中的最低有效 64 位。 */ public long getLeastSignificantBits() { return leastSigBits; } /** * 返回此 UUID 的 128 位值中的最高有效 64 位。 * * @return 此 UUID 的 128 位值中最高有效 64 位。 */ public long getMostSignificantBits() { return mostSigBits; } /** * 與此 {@code UUID} 相關(guān)聯(lián)的版本號. 版本號描述此 {@code UUID} 是如何生成的。 * <p> * 版本號具有以下含意: * <ul> * <li>1 基于時間的 UUID * <li>2 DCE 安全 UUID * <li>3 基于名稱的 UUID * <li>4 隨機生成的 UUID * </ul> * * @return 此 {@code UUID} 的版本號 */ public int version() { // Version is bits masked by 0x000000000000F000 in MS long return (int) ((mostSigBits >> 12) & 0x0f); } /** * 與此 {@code UUID} 相關(guān)聯(lián)的變體號。變體號描述 {@code UUID} 的布局。 * <p> * 變體號具有以下含意: * <ul> * <li>0 為 NCS 向后兼容保留 * <li>2 <a rel="external nofollow" >IETF RFC 4122</a>(Leach-Salz), 用于此類 * <li>6 保留,微軟向后兼容 * <li>7 保留供以后定義使用 * </ul> * * @return 此 {@code UUID} 相關(guān)聯(lián)的變體號 */ public int variant() { // This field is composed of a varying number of bits. // 0 - - Reserved for NCS backward compatibility // 1 0 - The IETF aka Leach-Salz variant (used by this class) // 1 1 0 Reserved, Microsoft backward compatibility // 1 1 1 Reserved for future definition. return (int) ((leastSigBits >>> (64 - (leastSigBits >>> 62))) & (leastSigBits >> 63)); } /** * 與此 UUID 相關(guān)聯(lián)的時間戳值。 * * <p> * 60 位的時間戳值根據(jù)此 {@code UUID} 的 time_low、time_mid 和 time_hi 字段構(gòu)造。<br> * 所得到的時間戳以 100 毫微秒為單位,從 UTC(通用協(xié)調(diào)時間) 1582 年 10 月 15 日零時開始。 * * <p> * 時間戳值僅在在基于時間的 UUID(其 version 類型為 1)中才有意義。<br> * 如果此 {@code UUID} 不是基于時間的 UUID,則此方法拋出 UnsupportedOperationException。 * * @throws UnsupportedOperationException 如果此 {@code UUID} 不是 version 為 1 的 UUID。 */ public long timestamp() throws UnsupportedOperationException { checkTimeBase(); return (mostSigBits & 0x0FFFL) << 48// | ((mostSigBits >> 16) & 0x0FFFFL) << 32// | mostSigBits >>> 32; } /** * 與此 UUID 相關(guān)聯(lián)的時鐘序列值。 * * <p> * 14 位的時鐘序列值根據(jù)此 UUID 的 clock_seq 字段構(gòu)造。clock_seq 字段用于保證在基于時間的 UUID 中的時間唯一性。 * <p> * {@code clockSequence} 值僅在基于時間的 UUID(其 version 類型為 1)中才有意義。 如果此 UUID 不是基于時間的 UUID,則此方法拋出 * UnsupportedOperationException。 * * @return 此 {@code UUID} 的時鐘序列 * * @throws UnsupportedOperationException 如果此 UUID 的 version 不為 1 */ public int clockSequence() throws UnsupportedOperationException { checkTimeBase(); return (int) ((leastSigBits & 0x3FFF000000000000L) >>> 48); } /** * 與此 UUID 相關(guān)的節(jié)點值。 * * <p> * 48 位的節(jié)點值根據(jù)此 UUID 的 node 字段構(gòu)造。此字段旨在用于保存機器的 IEEE 802 地址,該地址用于生成此 UUID 以保證空間唯一性。 * <p> * 節(jié)點值僅在基于時間的 UUID(其 version 類型為 1)中才有意義。<br> * 如果此 UUID 不是基于時間的 UUID,則此方法拋出 UnsupportedOperationException。 * * @return 此 {@code UUID} 的節(jié)點值 * * @throws UnsupportedOperationException 如果此 UUID 的 version 不為 1 */ public long node() throws UnsupportedOperationException { checkTimeBase(); return leastSigBits & 0x0000FFFFFFFFFFFFL; } /** * 返回此{@code UUID} 的字符串表現(xiàn)形式。 * * <p> * UUID 的字符串表示形式由此 BNF 描述: * * <pre> * {@code * UUID = <time_low>-<time_mid>-<time_high_and_version>-<variant_and_sequence>-<node> * time_low = 4*<hexOctet> * time_mid = 2*<hexOctet> * time_high_and_version = 2*<hexOctet> * variant_and_sequence = 2*<hexOctet> * node = 6*<hexOctet> * hexOctet = <hexDigit><hexDigit> * hexDigit = [0-9a-fA-F] * } * </pre> * * </blockquote> * * @return 此{@code UUID} 的字符串表現(xiàn)形式 * @see #toString(boolean) */ @Override public String toString() { return toString(false); } /** * 返回此{@code UUID} 的字符串表現(xiàn)形式。 * * <p> * UUID 的字符串表示形式由此 BNF 描述: * * <pre> * {@code * UUID = <time_low>-<time_mid>-<time_high_and_version>-<variant_and_sequence>-<node> * time_low = 4*<hexOctet> * time_mid = 2*<hexOctet> * time_high_and_version = 2*<hexOctet> * variant_and_sequence = 2*<hexOctet> * node = 6*<hexOctet> * hexOctet = <hexDigit><hexDigit> * hexDigit = [0-9a-fA-F] * } * </pre> * * </blockquote> * * @param isSimple 是否簡單模式,簡單模式為不帶'-'的UUID字符串 * @return 此{@code UUID} 的字符串表現(xiàn)形式 */ public String toString(boolean isSimple) { final StringBuilder builder = new StringBuilder(isSimple ? 32 : 36); // time_low builder.append(digits(mostSigBits >> 32, 8)); if (false == isSimple) { builder.append('-'); } // time_mid builder.append(digits(mostSigBits >> 16, 4)); if (false == isSimple) { builder.append('-'); } // time_high_and_version builder.append(digits(mostSigBits, 4)); if (false == isSimple) { builder.append('-'); } // variant_and_sequence builder.append(digits(leastSigBits >> 48, 4)); if (false == isSimple) { builder.append('-'); } // node builder.append(digits(leastSigBits, 12)); return builder.toString(); } /** * 返回此 UUID 的哈希碼。 * * @return UUID 的哈希碼值。 */ @Override public int hashCode() { long hilo = mostSigBits ^ leastSigBits; return ((int) (hilo >> 32)) ^ (int) hilo; } /** * 將此對象與指定對象比較。 * <p> * 當且僅當參數(shù)不為 {@code null}、而是一個 UUID 對象、具有與此 UUID 相同的 varriant、包含相同的值(每一位均相同)時,結(jié)果才為 {@code true}。 * * @param obj 要與之比較的對象 * * @return 如果對象相同,則返回 {@code true};否則返回 {@code false} */ @Override public boolean equals(Object obj) { if ((null == obj) || (obj.getClass() != UUID.class)) { return false; } UUID id = (UUID) obj; return (mostSigBits == id.mostSigBits && leastSigBits == id.leastSigBits); } // Comparison Operations /** * 將此 UUID 與指定的 UUID 比較。 * * <p> * 如果兩個 UUID 不同,且第一個 UUID 的最高有效字段大于第二個 UUID 的對應(yīng)字段,則第一個 UUID 大于第二個 UUID。 * * @param val 與此 UUID 比較的 UUID * * @return 在此 UUID 小于、等于或大于 val 時,分別返回 -1、0 或 1。 * */ @Override public int compareTo(UUID val) { // The ordering is intentionally set up so that the UUIDs // can simply be numerically compared as two numbers return (this.mostSigBits < val.mostSigBits ? -1 : // (this.mostSigBits > val.mostSigBits ? 1 : // (this.leastSigBits < val.leastSigBits ? -1 : // (this.leastSigBits > val.leastSigBits ? 1 : // 0)))); } // ------------------------------------------------------------------------------------------------------------------- // Private method start /** * 返回指定數(shù)字對應(yīng)的hex值 * * @param val 值 * @param digits 位 * @return 值 */ private static String digits(long val, int digits) { long hi = 1L << (digits * 4); return Long.toHexString(hi | (val & (hi - 1))).substring(1); } /** * 檢查是否為time-based版本UUID */ private void checkTimeBase() { if (version() != 1) { throw new UnsupportedOperationException("Not a time-based UUID"); } } /** * 獲取{@link SecureRandom},類提供加密的強隨機數(shù)生成器 (RNG) * * @return {@link SecureRandom} */ public static SecureRandom getSecureRandom() { try { return SecureRandom.getInstance("SHA1PRNG"); } catch (NoSuchAlgorithmException e) { throw new UtilException(e); } } /** * 獲取隨機數(shù)生成器對象<br> * ThreadLocalRandom是JDK 7之后提供并發(fā)產(chǎn)生隨機數(shù),能夠解決多個線程發(fā)生的競爭爭奪。 * * @return {@link ThreadLocalRandom} */ public static ThreadLocalRandom getRandom() { return ThreadLocalRandom.current(); } }
更新(新方法)
private String getCode(){ String code = RandomStringUtils.randomAlphanumeric(8); return code; }
RandomStringUtils
是 Apache Commons Lang 庫中的一個工具類,用于生成隨機字符串。randomAlphanumeric(8)
是RandomStringUtils
類的靜態(tài)方法,它接受一個整數(shù)參數(shù),指定生成字符串的長度。這里傳入?yún)?shù) 8,表示生成一個長度為8的隨機字符串。
RandomStringUtils.randomAlphanumeric() 方法是典型的時間換空間的實現(xiàn)。
這個方法會生成一個指定長度的隨機字符串,由數(shù)字和字母組成。它的具體實現(xiàn)會利用 Java 內(nèi)置的隨機數(shù)生成器 java.util.Random 生成隨機數(shù),然后通過循環(huán)逐個字符添加到生成的字符串中。因此,這個方法會消耗一定的時間和計算資源來生成隨機字符串。
相比較于其他實現(xiàn)方式,例如預(yù)先生成所有可能的隨機字符串并保存在內(nèi)存中,RandomStringUtils.randomAlphanumeric() 方法可以避免占用大量內(nèi)存空間。因此,我們可以將其視為一種時間換空間的實現(xiàn)方式,是在保證隨機性的同時,盡可能地減少內(nèi)存資源的占用。
總結(jié)
到此這篇關(guān)于JAVA生成八位不重復(fù)隨機數(shù)最快方法的文章就介紹到這了,更多相關(guān)JAVA生成八位不重復(fù)隨機數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java網(wǎng)絡(luò)編程實現(xiàn)多線程聊天
這篇文章主要為大家詳細介紹了Java網(wǎng)絡(luò)編程實現(xiàn)多線程聊天,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-07-07mybatis-plus的selectById(或者selectOne)在根據(jù)主鍵ID查詢實體對象的時候偶爾會出現(xiàn)nul
這篇文章主要介紹了mybatis-plus的selectById(或者selectOne)在根據(jù)主鍵ID查詢實體對象的時候偶爾會出現(xiàn)null的問題記錄,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09Mybatis-Plus中的@TableName 和 table-prefix使用
table-prefix 是一個全局配置,它會自動在所有表名前添加指定的前綴,這個配置對于那些使用一致命名約定的數(shù)據(jù)庫表非常有用,這篇文章主要介紹了Mybatis-Plus中的@TableName 和 table-prefix使用,需要的朋友可以參考下2024-08-08