单实例环境,不是分布式
需要流水号
/**
* 流水号生成器
*
* 年+天号+毫秒+随机数
* 2019+134+480+11位随机数
* 4+3+3+11 = 21位
*
*
* @author sxd
* @date 2019/5/14 9:55
*/
public class SerialCreater { public static final String SERIAL_FROMAT = "%s%s%s%s"; private String serialNum; public SerialCreater() {
this.serialNum = String.format(
SERIAL_FROMAT,
DateUtil.thisYear(),
Calendar.getInstance().get(Calendar.DAY_OF_YEAR),
DateUtil.thisMillsecond(),
random());
} public static String getSerial(){
return new SerialCreater().serialNum;
} private String random(){
Long a = new Random().nextLong();
Long b = DateUtil.current(false);
Long c = (a-b)>>>16;
return autoGenericCode(c);
} private String autoGenericCode(Long old){
String result = old.toString();
int length = result.length();
if (length > 11){
result = result.substring(0,11);
}else if (length < 11){
result = String.format("%011d", old);
}
return result;
} }
调用:
System.out.println(SerialCreater.getSerial());
测试生成100W,查看是否重复:
public static void main(String[] args) { Set<String> set = new HashSet<>();
System.out.println(set.size());
int a = 1000000;
for (int i = 0; i < a; i++) {
set.add(SerialCreater.getSerial());
} System.out.println(set.size());
}
并发100W,100W个线程测试是否重复:
/**
* @author sxd
* @date 2019/5/14 13:35
*/
public class RUnTest { static final ConcurrentHashMap<String,Integer> concurrentHashMap = new ConcurrentHashMap<>(); public static void main(String[] args) { System.out.println(concurrentHashMap.size());
int a = 1000000;
for (int i = 0; i < a; i++) {
MyThread my = new MyThread();
my.run();
} System.out.println(concurrentHashMap.size());
} static class MyThread implements Runnable{ @Override
public void run() {
concurrentHashMap.put(SerialCreater.getSerial(),1);
}
}
}