Implementation example of SpringBoot custom snowflake algorithm generation ID
Snowflake is a distributed algorithm that generates unique IDs, introduced by Twitter. It can generate non-repetitive, chronological globally unique IDs. A typical Snowflake ID consists of 64 bits, usually divided as follows:
- 1-bit sign bit (always 0, indicating a positive number)
- 41-bit timestamp (millisecond level, indicating the offset of the current time relative to a certain start time)
- 10-bit machine ID (usually divided into data center ID and machine ID)
- 12-bit serial number (represents a counter within milliseconds)
Below is a custom snowflake algorithm to generate unique IDs. This implementation is similar to Twitter's Snowflake algorithm, with thread safety in mind.
public class SnowflakeIDGenerator { // Start timestamp (2020-01-01 00:00:00) private final long twepoch = 1577836800000L; // The number of bits occupied by each part private final long workerIdBits = 5L; private final long datacenterIdBits = 5L; private final long sequenceBits = 12L; // Maximum value private final long maxWorkerId = -1L ^ (-1L << workerIdBits); private final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits); // Displacement private final long workerIdShift = sequenceBits; private final long datacenterIdShift = sequenceBits + workerIdBits; private final long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits; // Mask private final long sequenceMask = -1L ^ (-1L << sequenceBits); private long workerId; private long datacenterId; private long sequence = 0L; private long lastTimestamp = -1L; public SnowflakeIDGenerator(long workerId, long datacenterId) { if (workerId > maxWorkerId || workerId < 0) { throw new IllegalArgumentException(("worker Id can't be greater than %d or less than 0", maxWorkerId)); } if (datacenterId > maxDatacenterId || datacenterId < 0) { throw new IllegalArgumentException(("datacenter Id can't be greater than %d or less than 0", maxDatacenterId)); } = workerId; = datacenterId; } public synchronized long nextId() { long timestamp = timeGen(); if (timestamp < lastTimestamp) { throw new RuntimeException(("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp)); } if (lastTimestamp == timestamp) { sequence = (sequence + 1) & sequenceMask; if (sequence == 0) { timestamp = tilNextMillis(lastTimestamp); } } else { sequence = 0L; } lastTimestamp = timestamp; return ((timestamp - twepoch) << timestampLeftShift) | (datacenterId << datacenterIdShift) | (workerId << workerIdShift) | sequence; } protected long tilNextMillis(long lastTimestamp) { long timestamp = timeGen(); while (timestamp <= lastTimestamp) { timestamp = timeGen(); } return timestamp; } protected long timeGen() { return (); } public static void main(String[] args) { SnowflakeIDGenerator generator = new SnowflakeIDGenerator(1, 1); for (int i = 0; i < 10; i++) { (()); } } }
illustrate
-
Initialization parameters:
-
twepoch
: Custom starting timestamp (can be any time in the past), ensuring that the generated ID is unique and ordered. -
workerIdBits
anddatacenterIdBits
: The number of bits (usually 5 bits) of the work node ID and the data center ID, respectively. -
sequenceBits
: The number of digits representing the serial number (usually 12 digits).
-
-
Maximum value calculation:
-
maxWorkerId
andmaxDatacenterId
: The maximum value calculated based on the number of digits to ensure that the ID is within a reasonable range.
-
-
Displacement amount:
-
workerIdShift
,datacenterIdShift
,timestampLeftShift
: Used to move each part of the data to the correct position.
-
-
Mask:
-
sequenceMask
: Make sure the serial number is cycling between 0 and 4095.
-
-
method:
-
nextId
: Generate unique IDs and use synchronization blocks to ensure thread safety. -
tilNextMillis
: Wait until the next millisecond. -
timeGen
: Get the current timestamp.
-
Example of usage
Run the above code and you will see the generated unique IDs, which are incremented in chronological order, each ID contains information about the timestamp, data center ID, worker node ID, and serial number.
This is the end of this article about the implementation example of SpringBoot custom snowflake algorithm generation ID generation. For more related SpringBoot snowflake algorithm generation ID content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!
Related Articles
Summary of knowledge related to SpringMVC data output
Today, I will take you to learn about SpringMVC. The article provides a very detailed code example for SpringMVC data output, which is very helpful to those who are learning. Friends who need it can refer to it.2021-06-06Instructions for mybatis if judgment not to use boolean value
This article mainly introduces the explanation of mybatis' if judgment, not to use boolean value. It has good reference value and hopes it will be helpful to everyone. Let's take a look with the editor2020-11-11Detailed explanation of OGNL usage tutorial in MyBatis
Some people may not know that OGNL is used in MyBatis, and some people know that OGNL is used but do not know how to use it in MyBatis. The following article mainly introduces the tutorial on using OGNL in MyBatis. The article introduces it in very detailed. Friends who need it can refer to it. Let’s take a look together.2017-06-06Resty minimalist restful framework quick access to Spring
This article mainly introduces the detailed instructions for quick access to Spring by Resty's minimalist restful framework. Friends in need can refer to it for reference. I hope it can be helpful. I wish you more progress and get a promotion as soon as possible.2022-03-03Implementation of Spring Boot Admin microservice application monitoring
This article mainly introduces Spring Boot Admin microservice application monitoring. The article introduces the example code in detail, which has certain reference learning value for everyone's study or work. Friends who need it, please learn with the editor below.2019-10-10Spring security solves the problem of obtaining user information as null or string value
This article mainly introduces the solution of spring security to obtain user information as null or string value. It has good reference value. I hope it will be helpful to everyone. If there are any errors or no complete considerations, I hope you will be very encouraged.2024-03-03Detailed explanation of the code of Springmvc file upload implementation of ssm framework
This article mainly introduces the detailed explanation of the code uploading and realization of the ssm framework Springmvc file. The example code is introduced in this article in detail, which has certain reference value for everyone's learning or work. Friends who need it can refer to it.2020-07-07Idea cannot display the directory structure after opening the project, and can only display the .iml file problem
This article mainly introduces the problem that Idea cannot display the directory structure after opening the project, and can only display the .iml file. It has good reference value. I hope it will be helpful to everyone. If there are any errors or no complete considerations, I would like to give you advice.2024-08-08Solution for encoding errors in BMIDE environment import project
This article mainly introduces the coding error solution for BMIDE environment import project. The example code is introduced in this article in detail, which has certain reference value for everyone's study or work. Friends who need it can refer to it.2020-10-10Java programming: Multi-thread deadlock and communication between threads are simple code
This article mainly introduces Java programming, multi-thread deadlock and simple implementation code for communication between threads, which has certain reference value. Friends who need it can learn about it.2017-10-10