zoukankan      html  css  js  c++  java
  • 生成uuid

    Base64压缩UUID长度替换Hibernate原有UUID生成器

    本文来自http://my.oschina.net/noahxiao/blog/132277,个人储藏使用

    1、背景

    在采用Hibernate做对象映射时,我一直都采用UUID来做主键。由于Hibernate的UUID需要占用32位的字符,所以一般都会让人感觉响效率且增加存储占用。

    我在查看公司项目时发现了一种比较好的生成UUID的方法,就是将UUID数据进行Base64化。觉得比较有意义拿出来给大家分享。

    2、传统UUID

    a、java.util.UUID

    Java中的UUID采用RFC 4122的标准,按标准数据按16进制进行表示(36个字符)。如:f81d4fae-7dec-11d0-a765-00a0c91e6bf6

    b、Hibernate UUID

    Hibernate默认产生的UUID与RFC 4122标准相比,去掉了没有用的"-"分割符号,所以更短(32个字符)。如:f81d4fae7dec11d0a76500a0c91e6bf6

    3、Base64格式的UUID

    由于Base64编码使用的字符包括大小写字母各26个,加上10个数字,和加号“+”,斜杠“/”,一共64个字符。所以才有Base64名字的由来。Base64相当于使用64进制来表示数据,相同长度位数的情况下要比16进制表示更多的内容。

    由于UUID标准数据总共是128-bit,所以我们就可以对这个128-bit重新进行Base64编码。

    128-bit的UUID在Java中表示为两个long型数据,可以采用java.util.UUID中的 getLeastSignificantBits与getMostSignificantBits分别获得两个long(64-bit)。再通过 Base64转码就可以获得我们所要的UUID。

    UuidUtils工具类

    复制代码
    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直接传参。

    4、Hibernate的UUID生成器

    由于Hibernate4对SessionImplementor的包做出了调整所以ID生成器的实现稍有不同(import)。

    a、Hibernate3

    复制代码
    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();
        }
    }
    复制代码

    b、Hibernate4

    复制代码
    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();
        }
     
    }
    复制代码

    映射中使用Base64的UUID

    @Id
        @GenericGenerator(name = "uuidGenerator", strategy = "org.noahx.uuid.Base64UuidGenerator")
        @GeneratedValue(generator = "uuidGenerator")
        @Column("UUID", length = 22)
        private String uuid;

    Base58简介

    Base58采用的字符集合为 “123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ”,从这不难看 出,Base58是纯数字与字母组成而且去掉了容易引起视觉混淆的字符(0:数字零,O:大写O,I:大写i,l:小写L)。9个数字+49个字母=58 个。由于没有特殊字符所以在采用鼠标双击或移动设备选择时可以自动识别全选。

    Base58本身就是URLSafe。Base64的URFSafe模式虽然已经对URL支持的比较好,但UUID中还是包含“-或_”。

    目前流行的比特币,采用的就是Base58Check编码,是在Base58基础上又增加了安全效验机制。

    三、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生成程序

    这个生成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();
        }
    }
    复制代码

    生成UUID的效果

    1、Base64的效果

    复制代码
    M0ISICCxQi6sP-KIq3kFOw
    11YozyYYTvKmuUXpRDvoJA
    KlZnS-MuT2m3d-the2chxg
    8J3SC10AQzqZr6Im8V2xYA
    ES1UiFTGTHqn6ADU5YW0aw
    1usa208oT1q7FitKbQHH5Q
    53aDQZxKTGyqmKCzDnBwYQ
    SVVjViEoQXayWB9_JknKqQ
    fP6znJIAT1uGMN9HW5o8cw
    YR-2-kKmSOubhGr2LpFCgQ
    复制代码

    可以看到有-与_字符。大家可以双击上面包含-的UUID,得到只选中部分的效果。

    2、Base58的效果

    复制代码
    MqJqC2rtZLkuHys6ed2Eai
    QrS5w2t5etpRY3zTR1BAEJ
    Qd6wcFFVz2ZSQb3voGGj8P
    75bJdWMcEh6NhT51D5Uyju
    2L7kTgsktxMBKLkfAo2iWC
    UX2Twhbt1kstRziqc7iwCR
    9tZNKCeR93taLHU6PVy8hN
    HSn6JMibca4nG9URWokpwg
    8eL4SNz2a4puEW8fD4njsG
    GThFxPsdVUoZMfmKoEHwQX
    复制代码

    Base58与Base64(URLSafe)一样也只需21或22个字符就可以标示128位的UUID数据。基本一样的长度,看上去更舒服,当然以后就采用Base58来生成UUID。配合Hibernate的UUID生成器

     
  • 相关阅读:
    codeforces 459 C. Pashmak and Buses(思维)
    poj 2763 Housewife Wind(树链剖分+单点查询+区间修改)
    codeforces E. Phone Talks(dp)
    BZOJ 1036: [ZJOI2008]树的统计Count(树链剖分+单点更新+区间求和+区间求最大值)
    SPOJ
    hdu 3966 Aragorn's Story(树链剖分+区间修改+单点查询)
    codeforces H. Queries for Number of Palindromes(区间dp)
    codeforces 245 D. Restoring Table(位运算+思维)
    codeforces 402 D. Upgrading Array(数论+贪心)
    codeforces 793 D. Presents in Bankopolis(记忆化搜索)
  • 原文地址:https://www.cnblogs.com/lic309/p/4433966.html
Copyright © 2011-2022 走看看