项目中经常会用到id,一个项目中偶尔会使用到全局id,要求不重复且具有一定的查询效率,所以写了一个19位的不重复id生成器
public class IdWorker {
/**
* 一启动就创建一个worker,如果有多台机器,则workerID和datacenterID可以从配置文件中读取
*/
private static IdWorker worker = new IdWorker(1, 1, 1);
/**
* 生成一个ID
*
* @return
*/
public static long getId() {
return worker.nextId();
}
private long workerId;
private long datacenterId;
private long sequence;
private IdWorker(long workerId, long datacenterId, long sequence) {
if (workerId > maxWorkerId || workerId < 0) {
throw new IllegalArgumentException(
String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
}
if (datacenterId > maxDatacenterId || datacenterId < 0) {
throw new IllegalArgumentException(
String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId));
}
System.out.printf