IdUtil

Introduction

In a distributed environment, the generation of unique IDs is widely used, and there are various generation methods. Hutool provides a simple encapsulation for some commonly used generation strategies.

The unique ID generator utility class covers:

  • UUID
  • ObjectId (MongoDB)
  • Snowflake (Twitter)

Usage

UUID

UUID stands for Universally Unique Identifier. The JDK provides a Leach-Salz variant of UUID through java.util.UUID. In Hutool, generating a UUID string is done as follows:

// The generated UUID is a string with hyphens, similar to: a5c8a5e8-df2b-4706-bea4-08d0939410e3
String uuid = IdUtil.randomUUID();

// The generated UUID is a string without hyphens, similar to: b17f24ff026d40949c85a24f4f375d42
String simpleUUID = IdUtil.simpleUUID();

Note Hutool rewrites the logic of java.util.UUID and uses the corresponding class cn.hutool.core.lang.UUID to generate a UUID string without hyphens, which doubles the performance.

ObjectId

ObjectId is a unique ID generation strategy for MongoDB database, which is a variant of UUID version1. For details, see the article “Distributed Unique ID Generation Methods” at http://calvin1978.blogcn.com/articles/uuid.html.

Hutool provides a simple encapsulation for this through cn.hutool.core.lang.ObjectId, and the quick creation method is as follows:

// Generate a string similar to: 5b9e306a4df4f8c54a39fb0c
String id = ObjectId.next();

// Method 2: Available from Hutool 4.1.14 onwards
String id2 = IdUtil.objectId();

Snowflake

In distributed systems, there are some scenarios that require globally unique IDs. Sometimes, we hope to use a simpler ID, and we hope that the ID can be generated in an orderly manner according to time. Twitter’s Snowflake algorithm is such a generator.

The usage is as follows:

// Parameter 1 is the terminal ID
// Parameter 2 is the data center ID
Snowflake snowflake = IdUtil.getSnowflake(1, 1);
long id = snowflake.nextId();

// Simple usage
long id = IdUtil.getSnowflakeNextId();
String id = IdUtil.getSnowflakeNextIdStr();

Note IdUtil.createSnowflake creates a new Snowflake object each time it is called, and IDs created by different Snowflake objects may overlap. Therefore, please maintain this object as a singleton or use IdUtil.getSnowflake to use the global singleton object.