java 生成按照生成时间排序的UUID

 项目中使用UUID作为主键,但无论是mysql生成的UUID还是java的randomUUID都是无序的,很不方便查看数据的生成顺序,这里写了一个有序UUID的生成类,使用起来十分方便,而且可以按照生成时间进行排序,生成方法简单高效,方便使用者再次基础上进行扩展。


package app.core.util;

import java.net.InetAddress;
import java.util.UUID;

/**
 *
 * @author Beyound
 *
 */
public class UtilUUID{
    private static final String sep = "-";

    public static String generate() {
        return format(System.currentTimeMillis())+"-"+
                format(System.currentTimeMillis()>>4)+ "-"+format(getIP())+"-"+ formatInt( getCount());
    }

    public static void main(String[] args) {
        UUID.randomUUID().toString();
        System.out.println(generate());
//        System.out.println(format());
    }

    protected static String format(int value) {
        int index = value%chars.length;
        value = value/chars.length;
        if(value>0){
            return  format(value)+chars[index];
        }else return ""+chars[index];
    }
    protected static String formatInt(int value) {
        String re = format(value);
        re="000000"+re;
        return re.substring(re.length()-7);
    }
    static char[] chars = {'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 format(Long value){
        Long index = value%chars.length;
        value = value/chars.length;
        if(value>0){
            return format(value)+chars[index.intValue()];
        }else return ""+chars[index.intValue()];
    }
    public static int toInt(byte[] bytes) {
        int result = 0;
        for ( int i = 0; i < 4; i++ ) {
            result = ( result << 8 ) - Byte.MIN_VALUE + (int) bytes[i];
        }
        return result;
    }
    private static final int IP;
    static {
        int ipadd;
        try {
            ipadd = toInt( InetAddress.getLocalHost().getAddress() );
        }
        catch (Exception e) {
            ipadd = 0;
        }
        IP = ipadd;
    }
    private static Integer counter = (Integer) 0;
    private static final int JVM = (int) ( System.currentTimeMillis() >>> 8 );

    protected static Integer getCount() {
        synchronized(UtilUUID.class) {
            return counter=counter<0?0:++counter;
        }
    }
    protected static int getIP() {
        return IP;
    }

}

 

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值