本文來自http://my.oschina.net/noahxiao/blog/132277,我的儲藏使用html
在採用Hibernate作對象映射時,我一直都採用UUID來作主鍵。因爲Hibernate的UUID須要佔用32位的字符,因此通常都會讓人感受響效率且增長存儲佔用。java
我在查看公司項目時發現了一種比較好的生成UUID的方法,就是將UUID數據進行Base64化。以爲比較有意義拿出來給你們分享。git
Java中的UUID採用RFC 4122的標準,按標準數據按16進制進行表示(36個字符)。如:f81d4fae-7dec-11d0-a765-00a0c91e6bf6apache
Hibernate默認產生的UUID與RFC 4122標準相比,去掉了沒有用的"-"分割符號,因此更短(32個字符)。如:f81d4fae7dec11d0a76500a0c91e6bf6安全
因爲Base64編碼使用的字符包括大小寫字母各26個,加上10個數字,和加號「+」,斜槓「/」,一共64個字符。因此纔有Base64名字的由來。Base64至關於使用64進制來表示數據,相同長度位數的狀況下要比16進製表示更多的內容。session
因爲UUID標準數據總共是128-bit,因此咱們就能夠對這個128-bit從新進行Base64編碼。app
128-bit的UUID在Java中表示爲兩個long型數據,能夠採用java.util.UUID中的 getLeastSignificantBits與getMostSignificantBits分別得到兩個long(64-bit)。再經過 Base64轉碼就能夠得到咱們所要的UUID。dom
UuidUtils工具類ide
package org.noahx.uuid; import org.apache.commons.codec.binary.Base64; import java.util.UUID; public abstract class UuidUtils { public static String uuid() { UUID uuid = UUID.randomUUID(); return uuid.toString(); } public static String compressedUuid() { UUID uuid = UUID.randomUUID(); return compressedUUID(uuid); } protected static String compressedUUID(UUID uuid) { byte[] byUuid = new byte[16]; long least = uuid.getLeastSignificantBits(); long most = uuid.getMostSignificantBits(); long2bytes(most, byUuid, 0); long2bytes(least, byUuid, 8); String compressUUID = Base64.encodeBase64URLSafeString(byUuid); return compressUUID; } protected static void long2bytes(long value, byte[] bytes, int offset) { for (int i = 7; i > -1; i--) { bytes[offset++] = (byte) ((value >> 8 * i) & 0xFF); } } public static String compress(String uuidString) { UUID uuid = UUID.fromString(uuidString); return compressedUUID(uuid); } public static String uncompress(String compressedUuid) { if (compressedUuid.length() != 22) { throw new IllegalArgumentException("Invalid uuid!"); } byte[] byUuid = Base64.decodeBase64(compressedUuid + "=="); long most = bytes2long(byUuid, 0); long least = bytes2long(byUuid, 8); UUID uuid = new UUID(most, least); return uuid.toString(); } protected static long bytes2long(byte[] bytes, int offset) { long value = 0; for (int i = 7; i > -1; i--) { value |= (((long) bytes[offset++]) & 0xFF) << 8 * i; } return value; } }
經過調用UuidUtils.compressedUuid()方法就能夠得到個人須要的UUID字符串(22個字符,128-bit的Base64只須要22個字符)。如:BwcyZLfGTACTz9_JUxSnyA工具
比Hibernate32個字符還短了10個字符。
在處理Base64時,這裏用到了apache的commons-codec編碼工具包,由於它提供了簡單的編碼轉換方法。並且還有 encodeBase64URLSafeString方法,採用URL安全方式生成Base64編碼。默認的Base64含有+與/字符,若是這種編碼出 如今URL中將形成混亂。URL安全方式採用了-替換+,_替換/,並去掉告終束==。很是適合Web直接傳參。
因爲Hibernate4對SessionImplementor的包作出了調整因此ID生成器的實現稍有不一樣(import)。
package org.noahx.uuid; import org.hibernate.HibernateException; import org.hibernate.engine.SessionImplementor; import org.hibernate.id.IdentifierGenerator; import java.io.Serializable; public class Base64UuidGenerator implements IdentifierGenerator { @Override public Serializable generate(SessionImplementor session, Object object) throws HibernateException { return UuidUtils.compressedUuid(); } }
package org.noahx.uuid; import org.hibernate.HibernateException; import org.hibernate.engine.spi.SessionImplementor; import org.hibernate.id.IdentifierGenerator; import java.io.Serializable; public class Base64UuidGenerator implements IdentifierGenerator { @Override public Serializable generate(SessionImplementor session, Object object) throws HibernateException { return UuidUtils.compressedUuid(); } }
@Id
@GenericGenerator(name = "uuidGenerator", strategy = "org.noahx.uuid.Base64UuidGenerator")
@GeneratedValue(generator = "uuidGenerator")
@Column("UUID", length = 22)
private String uuid;
Base58採用的字符集合爲 「123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ」,從這不難看 出,Base58是純數字與字母組成並且去掉了容易引發視覺混淆的字符(0:數字零,O:大寫O,I:大寫i,l:小寫L)。9個數字+49個字母=58 個。因爲沒有特殊字符因此在採用鼠標雙擊或移動設備選擇時能夠自動識別全選。
Base58自己就是URLSafe。Base64的URFSafe模式雖然已經對URL支持的比較好,但UUID中仍是包含「-或_」。
目前流行的比特幣,採用的就是Base58Check編碼,是在Base58基礎上又增長了安全效驗機制。
因爲Base58最近才興起,Java與Apache Commons中並不包含編碼器。
package org.noahx.uuid.utils; import java.io.UnsupportedEncodingException; import java.math.BigInteger; /** * Created with IntelliJ IDEA. * User: noah * Date: 8/2/13 * Time: 10:36 AM * To change this template use File | Settings | File Templates. */ public class Base58 { public static final char[] ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz".toCharArray(); private static final int[] INDEXES = new int[128]; static { for (int i = 0; i < INDEXES.length; i++) { INDEXES[i] = -1; } for (int i = 0; i < ALPHABET.length; i++) { INDEXES[ALPHABET[i]] = i; } } /** * Encodes the given bytes in base58. No checksum is appended. */ public static String encode(byte[] input) { if (input.length == 0) { return ""; } input = copyOfRange(input, 0, input.length); // Count leading zeroes. int zeroCount = 0; while (zeroCount < input.length && input[zeroCount] == 0) { ++zeroCount; } // The actual encoding. byte[] temp = new byte[input.length * 2]; int j = temp.length; int startAt = zeroCount; while (startAt < input.length) { byte mod = divmod58(input, startAt); if (input[startAt] == 0) { ++startAt; } temp[--j] = (byte) ALPHABET[mod]; } // Strip extra '1' if there are some after decoding. while (j < temp.length && temp[j] == ALPHABET[0]) { ++j; } // Add as many leading '1' as there were leading zeros. while (--zeroCount >= 0) { temp[--j] = (byte) ALPHABET[0]; } byte[] output = copyOfRange(temp, j, temp.length); try { return new String(output, "US-ASCII"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); // Cannot happen. } } public static byte[] decode(String input) throws IllegalArgumentException { if (input.length() == 0) { return new byte[0]; } byte[] input58 = new byte[input.length()]; // Transform the String to a base58 byte sequence for (int i = 0; i < input.length(); ++i) { char c = input.charAt(i); int digit58 = -1; if (c >= 0 && c < 128) { digit58 = INDEXES[c]; } if (digit58 < 0) { throw new IllegalArgumentException("Illegal character " + c + " at " + i); } input58[i] = (byte) digit58; } // Count leading zeroes int zeroCount = 0; while (zeroCount < input58.length && input58[zeroCount] == 0) { ++zeroCount; } // The encoding byte[] temp = new byte[input.length()]; int j = temp.length; int startAt = zeroCount; while (startAt < input58.length) { byte mod = divmod256(input58, startAt); if (input58[startAt] == 0) { ++startAt; } temp[--j] = mod; } // Do no add extra leading zeroes, move j to first non null byte. while (j < temp.length && temp[j] == 0) { ++j; } return copyOfRange(temp, j - zeroCount, temp.length); } public static BigInteger decodeToBigInteger(String input) throws IllegalArgumentException { return new BigInteger(1, decode(input)); } // // number -> number / 58, returns number % 58 // private static byte divmod58(byte[] number, int startAt) { int remainder = 0; for (int i = startAt; i < number.length; i++) { int digit256 = (int) number[i] & 0xFF; int temp = remainder * 256 + digit256; number[i] = (byte) (temp / 58); remainder = temp % 58; } return (byte) remainder; } // // number -> number / 256, returns number % 256 // private static byte divmod256(byte[] number58, int startAt) { int remainder = 0; for (int i = startAt; i < number58.length; i++) { int digit58 = (int) number58[i] & 0xFF; int temp = remainder * 58 + digit58; number58[i] = (byte) (temp / 256); remainder = temp % 256; } return (byte) remainder; } private static byte[] copyOfRange(byte[] source, int from, int to) { byte[] range = new byte[to - from]; System.arraycopy(source, from, range, 0, range.length); return range; } }
這個生成UUID程序包含了Base64(URLSafe)與Base58兩種編碼。
package org.noahx.uuid.util; import org.apache.commons.codec.binary.Base64; import java.nio.ByteBuffer; import java.util.UUID; public abstract class UuidUtils { public static String uuid() { UUID uuid = UUID.randomUUID(); return uuid.toString(); } public static String base64Uuid() { UUID uuid = UUID.randomUUID(); return base64Uuid(uuid); } protected static String base64Uuid(UUID uuid) { ByteBuffer bb = ByteBuffer.wrap(new byte[16]); bb.putLong(uuid.getMostSignificantBits()); bb.putLong(uuid.getLeastSignificantBits()); return Base64.encodeBase64URLSafeString(bb.array()); } public static String encodeBase64Uuid(String uuidString) { UUID uuid = UUID.fromString(uuidString); return base64Uuid(uuid); } public static String decodeBase64Uuid(String compressedUuid) { byte[] byUuid = Base64.decodeBase64(compressedUuid); ByteBuffer bb = ByteBuffer.wrap(byUuid); UUID uuid = new UUID(bb.getLong(), bb.getLong()); return uuid.toString(); } public static String base58Uuid() { UUID uuid = UUID.randomUUID(); return base58Uuid(uuid); } protected static String base58Uuid(UUID uuid) { ByteBuffer bb = ByteBuffer.wrap(new byte[16]); bb.putLong(uuid.getMostSignificantBits()); bb.putLong(uuid.getLeastSignificantBits()); return Base58.encode(bb.array()); } public static String encodeBase58Uuid(String uuidString) { UUID uuid = UUID.fromString(uuidString); return base58Uuid(uuid); } public static String decodeBase58Uuid(String base58uuid) { byte[] byUuid = Base58.decode(base58uuid); ByteBuffer bb = ByteBuffer.wrap(byUuid); UUID uuid = new UUID(bb.getLong(), bb.getLong()); return uuid.toString(); } }
M0ISICCxQi6sP-KIq3kFOw
11YozyYYTvKmuUXpRDvoJA
KlZnS-MuT2m3d-the2chxg 8J3SC10AQzqZr6Im8V2xYA ES1UiFTGTHqn6ADU5YW0aw 1usa208oT1q7FitKbQHH5Q 53aDQZxKTGyqmKCzDnBwYQ SVVjViEoQXayWB9_JknKqQ fP6znJIAT1uGMN9HW5o8cw YR-2-kKmSOubhGr2LpFCgQ
能夠看到有-與_字符。你們能夠雙擊上面包含-的UUID,獲得只選中部分的效果。
MqJqC2rtZLkuHys6ed2Eai
QrS5w2t5etpRY3zTR1BAEJ
Qd6wcFFVz2ZSQb3voGGj8P
75bJdWMcEh6NhT51D5Uyju
2L7kTgsktxMBKLkfAo2iWC
UX2Twhbt1kstRziqc7iwCR
9tZNKCeR93taLHU6PVy8hN
HSn6JMibca4nG9URWokpwg
8eL4SNz2a4puEW8fD4njsG
GThFxPsdVUoZMfmKoEHwQX
Base58與Base64(URLSafe)同樣也只需21或22個字符就能夠標示128位的UUID數據。基本同樣的長度,看上去更舒服,固然之後就採用Base58來生成UUID。配合Hibernate的UUID生成器