Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to implement Snowflake algorithm with Hutool

Shulou Source: shulou.com Published: 2022-06-01 05:57:09 09月22日 Update

This article introduces the relevant knowledge of "how to achieve snowflake algorithm in Hutool". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

If you are asked about distributed unique identification in the interview, but do not answer the snowflake algorithm, then it is a bit unreasonable.

About the snowflake algorithm in distributed unique identification, there are many introductions on the network, it is only an algorithm, it can be implemented in different languages such as Python,Java. Even if it is the same language, its implementation is different.

However, there is another tool class, which is

Cn.hutool hutool-all 5.4.2

The snowflake algorithm is also implemented and provided internally. Here, we take it as a case to explain the snowflake algorithm.

Cn.hutool.core.lang.Snowflake

The core method is the following

Public synchronized long nextId () {/ / get the current timestamp long timestamp = genTime (); / / lastTimestamp means that the last time your program gets a distributed unique identification timestamp (ms) / / A machine normally, timestamp is greater than lastTimestamp. If timestamp

< lastTimestamp表明服务器的时间有问题,存在时钟后退. if (timestamp < lastTimestamp) { // 容忍2秒内的时钟后退 if(lastTimestamp - timestamp < 2000){ timestamp = lastTimestamp; } else{ // 如果服务器时间有问题(时钟后退) 报错。 throw new IllegalStateException(StrUtil.format("Clock moved backwards. Refusing to generate id for {}ms", lastTimestamp - timestamp)); } } if (timestamp == lastTimestamp) { // 相同毫秒内,序列号自增 sequence = (sequence + 1) & sequenceMask; // 同一毫秒的序列数已经达到最大 if (sequence == 0) { // 循环等待下一个时间 timestamp = tilNextMillis(lastTimestamp); } } else {// timestamp >

LastTimestamp / / within different milliseconds, the sequence number is set to 0 sequence = 0L;}

LastTimestamp = timestamp

/ / by bitwise or splicing the parts together return ((timestamp-twepoch))

Tags: Algorithm snowflake time part sequence identity different distributed serial number clock content that is situation more server machine case knowledge language problem Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Microsoft Shulou Information Shulou Technology Redmi MySQL