单机 随机数生成规则

总是需要生成,我就记录一下。如果 你是多个服务情况下,自己加个分布式锁就ok

package com.huifenqi.jedi.channel.alipay.util;

import java.util.Date;
import java.util.Random;

/**
 * 非线程安全 id生成器
 * @author [email protected]
 * @date 2019/10/23 10:39:18
 */
public class IdGeneratorUtil {

    /**
     * 获取一定长度的随机字符串
     * @param length 字符串的长度
     * @return 指定长度的随机字符串
     */
    public static String getRandomStringChars(Integer length) {
        if (length == null || length.intValue() == 0) {
            length = 3;
        }
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    /**
     * 获取一定长度的随机数字串
     * @param length 字符串的长度
     * @return 指定长度的随机字符串
     */
    public static String getRandomNumberChars(Integer length) {
        if (length == null || length.intValue() == 0) {
            length = 3;
        }
        String base = "0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    /**
     * 获取随机字符串,格式: yyyyMMddHHmmssSSS + 指定长度的随机字符串
     *
     * @param date Date格式的时间,将转换成yyyyMMddHHmmssSSS格式
     * @param count
     *          count.length:几段随机字符串,比如count.length为3,则代表 第1段随机数、第2段随机数和第3段随机数 三段随机苏拼接
     *          count[n]:数据中具体的值,代表每段随机数的长度,比如count[0]=4,代表第1段随机数的长度为4。如果count[n]为null或0,则当前段的随机数长度为3
     * @return 随机字符串
     * @author [email protected]
     * @date 2019/10/23 10:46:52
     */
    public static String getRandomStringByLength(Date date, Integer... count) {
        if (date == null) {
            date = new Date();
        }
        if (count == null || count.length == 0) {
            count = new Integer[]{3, 3, 3};
        }
        StringBuffer random = new StringBuffer(DateUtil.formatDateSeventeen(date))
                // 拼接2位随机数字
                .append(getRandomNumberChars(2))
                // 拼接3位随机数字
                .append(getRandomNumberChars(3));
        // 拼接count.length段随机字符
        for (int i = 0; i < count.length; i ++) {
            random.append(getRandomStringChars(count[i]));
        }
        // 拼接4位随机数字
        random.append(getRandomNumberChars(4));
        return random.toString();
    }

    public static void main(String[] args) {
        String random = getRandomStringByLength(new Date(), 1, 2, 3, 4, 5);
        LogUtil.info("random ===>>> " + random);
    }
}

你可能感兴趣的:(其他)