如下代码,创建一个生成id的工具类:
1)使用final修饰类,让该工具类不能被基础
2)构造方法私有化,使得外部不能创建该类的对象
3)将DataTimeFomatter和Random类对象,在此是作为工具用的,设置成静态对象,可以节约内存
4)使用当下的年月日时分秒毫秒+2位随机数作为id,只要创建的频率不是特别高,基本上可以保证id的唯一性
5)生成返回值为Long型的静态方法,可通过类名打点访问
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;
}
}