本文主要是介绍java中用雪花算法生成64位的长整数,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
场景:
以Mysql为例,除过自增主键id,还有一些字段需要储存一些唯一值,此时选择雪花算法生成的长整型数字的重要性尤为重要,它比UUID就好多了,雪花算法生成的长整数在性能、排序性、唯一性、可读性、可扩展性和存储方面具有明显的优势,尤其是在需要快速生成大量唯一ID的分布式系统中。
雪花算法生成的长整型数字比UUID()生成的随机数的优势:
1.雪花算法生成一个64位的随机数工具类
import java.util.concurrent.atomic.AtomicLong;public class SnowflakeIdGenerator {private static final long START_EPOCH = 1672531200000L; // 2023-01-01T00:00:00Zprivate static final long SEQUENCE_BITS = 12;private static final long MACHINE_ID_BITS = 10;private static final long TIMESTAMP_LEFT_SHIFT = SEQUENCE_BITS + MACHINE_ID_BITS;private static final long MACHINE_ID_LEFT_SHIFT = SEQUENCE_BITS;private static final long SEQUENCE_MASK = -1L ^ (-1L << SEQUENCE_BITS);private static final long MACHINE_ID_MAX = -1L ^ (-1L << MACHINE_ID_BITS);private final long machineId;private final AtomicLong lastTimestamp = new AtomicLong(-1L);private final AtomicLong sequence = new AtomicLong(0L);public SnowflakeIdGenerator(long machineId) {if (machineId < 0 || machineId > MACHINE_ID_MAX) {throw new IllegalArgumentException(String.format("Machine ID must be between 0 and %d", MACHINE_ID_MAX));}this.machineId = machineId;}public synchronized long nextId() {long currentTimestamp = System.currentTimeMillis() - START_EPOCH;if (currentTimestamp < lastTimestamp.get()) {throw new RuntimeException("Clock moved backwards. Refusing to generate id");}if (currentTimestamp == lastTimestamp.get()) {long newSequence = sequence.incrementAndGet();if (newSequence > SEQUENCE_MASK) {currentTimestamp = waitNextMillis(currentTimestamp);newSequence = 0;}sequence.set(newSequence);} else {sequence.set(0);}lastTimestamp.set(currentTimestamp);// Generate the IDlong id = (currentTimestamp << TIMESTAMP_LEFT_SHIFT) | (machineId << MACHINE_ID_LEFT_SHIFT) | sequence.get();return ensureStartsWithOne(id);}private long ensureStartsWithOne(long id) {String idStr = Long.toString(id);// Ensure the string representation of the ID starts with '1'if (!idStr.startsWith("1")) {idStr = "1" + idStr;}return Long.parseLong(idStr);}private long waitNextMillis(long currentTimestamp) {while (currentTimestamp <= lastTimestamp.get()) {currentTimestamp = System.currentTimeMillis() - START_EPOCH;}return currentTimestamp;}// 示例代码public static void main(String[] args) {System.out.println(new SnowflakeIdGenerator(1).nextId());// 假设机器ID为1}
}
测试结果:
2.雪花算法生成几个64位的有序数工具类
import java.util.concurrent.atomic.AtomicLong;public class OrderedSnowflakeIdGenerator {private static final long START_EPOCH = 1672531200000L; // 2023-01-01T00:00:00Zprivate static final long SEQUENCE_BITS = 12;private static final long MACHINE_ID_BITS = 10;private static final long TIMESTAMP_LEFT_SHIFT = SEQUENCE_BITS + MACHINE_ID_BITS;private static final long MACHINE_ID_LEFT_SHIFT = SEQUENCE_BITS;private static final long SEQUENCE_MASK = -1L ^ (-1L << SEQUENCE_BITS);private static final long MACHINE_ID_MAX = -1L ^ (-1L << MACHINE_ID_BITS);private final long machineId;private final AtomicLong lastTimestamp = new AtomicLong(-1L);private final AtomicLong sequence = new AtomicLong(0L);public OrderedSnowflakeIdGenerator(long machineId) {if (machineId < 0 || machineId > MACHINE_ID_MAX) {throw new IllegalArgumentException(String.format("Machine ID must be between 0 and %d", MACHINE_ID_MAX));}this.machineId = machineId;}public synchronized long nextId() {long currentTimestamp = System.currentTimeMillis() - START_EPOCH;if (currentTimestamp < lastTimestamp.get()) {throw new RuntimeException("Clock moved backwards. Refusing to generate id");}if (currentTimestamp == lastTimestamp.get()) {// Increment the sequence numberlong newSequence = sequence.incrementAndGet();if (newSequence > SEQUENCE_MASK) {// If the sequence number overflows, wait until the next millisecondcurrentTimestamp = waitNextMillis(currentTimestamp);newSequence = 0;}sequence.set(newSequence);} else {// Reset the sequence number at the start of each millisecondsequence.set(0);}lastTimestamp.set(currentTimestamp);// Generate the IDlong id = (currentTimestamp << TIMESTAMP_LEFT_SHIFT) | (machineId << MACHINE_ID_LEFT_SHIFT) | sequence.get();return ensureStartsWithOne(id);}private long ensureStartsWithOne(long id) {String idStr = Long.toString(id);// Ensure the string representation of the ID starts with '1'if (!idStr.startsWith("1")) {idStr = "1" + idStr;}return Long.parseLong(idStr);}private long waitNextMillis(long currentTimestamp) {while (currentTimestamp <= lastTimestamp.get()) {currentTimestamp = System.currentTimeMillis() - START_EPOCH;}return currentTimestamp;}// 生成有序的几个长整型数字,还是得用循环 示例代码public static void main(String[] args) {OrderedSnowflakeIdGenerator generator = new OrderedSnowflakeIdGenerator(1); // 假设机器ID为1for (int i = 0; i < 10; i++) {System.out.println(generator.nextId());}}
}
效果图:
这篇关于java中用雪花算法生成64位的长整数的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!