import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class IdWorker {
protected static final Logger LOG = LoggerFactory.getLogger(IdWorker.class);
/**
* 每个节点的唯一数字ID
*/
private long workerId;
private long datacenterId;
private long sequence = 0L;
private long twepoch = 1288834974657L;
// 机器标识位数
private long workerIdBits = 5L;
// 数据中心标识位数
private long datacenterIdBits = 5L;
// 机器ID最大值
private long maxWorkerId = -1L ^ (-1L <
// 数据中心ID最大值
private long maxDatacenterId = -1L ^ (-1L <
// 毫秒内自增位
private long sequenceBits = 12L;
// 机器ID偏左移12位
private long workerIdShift = sequenceBits;
// 数据中心ID左移17位
private long datacenterIdShift = sequenceBits + workerIdBits;
// 时间毫秒左移22位
private long timestampLeftShift = sequenceBits + workerIdBits+ datacenterIdBits;
private long sequenceMask = -1L ^ (-1L <
private long lastTimestamp = -1L;
public IdWorker(final long workerId) {
super();
if (workerId > this.maxWorkerId || workerId
throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0",maxWorkerId));
}
this.workerId = workerId;
}
public IdWorker(long workerId, long datacenterId) {
// sanity check for workerId
if (workerId > maxWorkerId || workerId
throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0",m