雪花id生成代码,超级简单
代码如下:
package com.he.mock.controller;
import java.net.Inet4Address;
import java.net.UnknownHostException;
import java.util.Random;
public class SnowflakeIdWorker {
private static long workId;
private static long sequence = 0L;
private static long serviceId = Math.abs(System.getenv().hashCode()) % 32;
private static long lastTime = System.currentTimeMillis();
private static long maxSequence = (1 << 12) - 1;
static {
try {
workId = Math.abs(Inet4Address.getLocalHost().getHostAddress().hashCode()) % 32;
} catch (UnknownHostException e) {
workId = new Random().nextLong() % 32;
}
}
private SnowflakeIdWorker() {
}
public synchronized static Long nextId() {
long l = System.currentTimeMillis();
if (lastTime == l) {
++sequence;
} else {
lastTime = l;
sequence = 0;
}
if (sequence > maxSequence) {
nextId();
}
return lastTime << 22 | serviceId << 17 | workId << 12 | sequence;
}
}
使用代码如下:
public static void main(String[] args) throws InterruptedException {
Map<Long, Long> map = new ConcurrentHashMap<>();
for (int i = 0; i < 300; i++) {
new Thread(() -> {
for (int j = 0; j < 10000; j++) {
Long aLong = SnowflakeIdWorker.nextId();
map.put(aLong,aLong);
}
}).start();
}
Thread.sleep(1000);
System.out.println(map.size());
}
效率如下:
大概一秒钟300万个id生成出来把,推荐使用哦,支持高并发,疯狂for循环小伙伴,欢迎一键三连