基于时间UUID的妙用

1、jar包获取

https://github.com/cowtowncoder/java-uuid-generator/

<dependency>
  <groupId>com.fasterxml.uuid</groupId>
  <artifactId>java-uuid-generator</artifactId>
  <version>3.1.3</version>
</dependency>

2、基于时间UUID与随机UUID

//version=4
System.out.println(UUID.randomUUID().version());
//32位bd22291e39eb4736a55991497c6376d2
System.out.println(UUID.randomUUID().toString().replaceAll("-", ""));

TimeBasedGenerator gen = Generators.timeBasedGenerator(EthernetAddress.fromInterface());
UUID uuid = gen.generate();
//version=1
System.out.println(uuid.version());
//32位33304096c01311e58c16089e01cd1de9
System.out.println(uuid.toString().replaceAll("-", ""));

3、提取UUID中的时间

uuid.timestamp()时间戳以 100 毫微秒为单位,从 UTC(通用协调时间) 1582 年 10 月 15 日零时开始。

Date.getTime()   从1970 年 1 月 1 日 00:00:00 GMT)以来的指定毫秒数

1毫秒=1000微妙=1000000毫微秒

Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(uuid.timestamp()/1000000*100);
cal.add(Calendar.YEAR, 	1582-1970);
cal.add(Calendar.MONTH, 10);
cal.add(Calendar.DAY_OF_MONTH, 15);
//TODO:输出2016-02-24 17:06:14,其实当前系统时间是2016-01-21 17:06:14,有几天的误差
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(cal.getTime()));

4、作用

sql中取max(pk)即是最后一次处理的记录,不用先取max(处理时间)再根据max时间找记录。


你可能感兴趣的:(uuid,基于时间)