短id生成

1.最多11位

2.一微秒内,最多100个不重复

3.最多支持到2100年,通过调整常量库,可以延长该期限

4.需要joda-time和guava(guava主要用于new Map)

public class SIDUtil {
    private static final Integer I_Y = 2000;// 起始年
    private static Integer I_Y_C = 0;// 盐循环
    private static final Integer I_M = 1;
    private static final String KEYS = "q,w,e,r,t,y,u,i,o,p,a,s,d,f,g,h,j,k,l,z,x,c,v,b,n,m,Q,W,E,R,T,Y,U,I,O,P,A,S,D,F,G,H,J,K,L,Z,X,C,V,B,N,M,1,2,3,4,5,6,7,8,9,0,qw,we,er,rt,ty,yu,ui,io,op,as,sd,df,fg,gh,hj,jk,kl,zx,xc,cv,vb,bn,nm,qe,qr,qt,qy,qu,qi,qo,qp,ad,af,ag,ah,aj,zv,zb,zn";
    private static Map<Integer, String> KEYMAP_Y = Maps.newConcurrentMap();
    private static Map<Integer, String> KEYMAP_M = Maps.newConcurrentMap();

    static {
        String[] keys_ = KEYS.split(",");
        Integer size = keys_.length;
        for (int i = 0; i < size; i++) {
            KEYMAP_Y.put(I_Y + i, keys_[i]);
        }
        for (int i = 0; i < size; i++) {
            KEYMAP_M.put(I_M + i, keys_[i]);
        }
    }

    public static String getId() {
        I_Y_C = I_Y_C + 1;
        if (I_Y_C >= KEYMAP_M.size()) {
            I_Y_C = 0;
        }
        DateTime d = DateTime.now();
        int y = d.getYear();
        int m = d.getMonthOfYear();
        int day = d.getDayOfMonth();
        int h = d.getHourOfDay();
        int mi = d.getMinuteOfHour();
        int ss = d.getSecondOfMinute();
        String sss = DateUtil.nowSSS(d);
//        int ws = Integer.parseInt(sss);// 原谅我没找到获取毫秒的方法
        int ws1 = Integer.parseInt(sss.substring(0, 2));
        int ws2 = Integer.parseInt(sss.substring(2, 3));
        return KEYMAP_Y.get(y) + KEYMAP_M.get(m) + KEYMAP_M.get(day) + KEYMAP_M.get(h) + KEYMAP_M.get(mi) + KEYMAP_M.get(ss) + KEYMAP_M.get(ws1) + ws2 + KEYMAP_M.get(I_Y_C);
    }

    public static void main(String[] args) {
        Map<String, String> mm = Maps.newHashMap();
        for (int i = 0; i < 10; i++) {
            String id = getId();
            mm.put(id, "1");
            System.out.println(id);
        }
        System.out.println(mm.size());
    }
}
发布者:songJian   点击数:509   发布时间:2022-06-30 00:54:51   更新时间:2022-06-30 00:56:27
正在加载评论...
相关文章