MYSQL不重复主键生成策略

转发地址忘记了(侵权必删)

    public static synchronized String getLocalTrmSeqNum() {
        sequence = sequence >= 999999 ? 1 : sequence + 1;
        String datetime = new SimpleDateFormat("yyyyHHmmss")    // 10位
                .format(new Date());
        String s = Integer.toString(sequence);
        return datetime + addLeftZero(s, length);
    }

    public static String addLeftZero(String s, int length) {

        int old = s.length();
        if (length > old) {
            char[] c = new char[length];
            char[] x = s.toCharArray();
            if (x.length > length) {
                throw new IllegalArgumentException(
                        "Numeric value is larger than intended length: " + s
                                + " LEN " + length);
            }
            int lim = c.length - x.length;
            for (int i = 0; i < lim; i++) {
                c[i] = '0';
            }
            System.arraycopy(x, 0, c, lim, x.length);
            return new String(c);
        }
        return s.substring(0, length);
    }

测试效果

    @Test
    public void test5(){
        String localTrmSeqNum = TourIdUtil.getLocalTrmSeqNum();
        System.out.println("localTrmSeqNum = " + localTrmSeqNum);       // localTrmSeqNum = 202016205500001
    }

猜你喜欢

转载自blog.csdn.net/weixin_44458365/article/details/107516339