Generate a unique id

The following code creates a tool class that generates an id:

1) Use final to modify the class so that the tool class cannot be used by the base

2) The constructor is privatized, so that objects of this class cannot be created externally

3) Set the DataTimeFomatter and Random class objects, which are used as tools here, as static objects, which can save memory

4) Use the current year, month, day, hour, minute, second, millisecond + 2 random numbers as the id, as long as the creation frequency is not particularly high, the uniqueness of the id can basically be guaranteed

5) Generate a static method with a return value of Long type, which can be accessed through the class name

public final class IdUtils {

    private IdUtils() {}

    private static DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");

    private static Random random = new Random();

    // 临时策略:使用“年月日时分秒毫秒”加2位随机数作为id
    public static Long getId() {
        LocalDateTime now = LocalDateTime.now();
        String dateTimeString = dateTimeFormatter.format(now);
        int randomNumber = random.nextInt(89) + 10;
        Long id = Long.valueOf(dateTimeString + randomNumber);
        return id;
    }

}

Guess you like

Origin blog.csdn.net/weixin_72125569/article/details/126948825