Get the App
SLTechnology News&Howtos  ›  Development  › 

How to write the snowflake algorithm code of Java

Shulou Source: shulou.com Published: 2022-06-03 07:21:23 11月15日 Update

This article introduces the relevant knowledge of "how to write the snowflake algorithm code of Java". 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!

Package com.java265.other;public class Test {/ / because the first bit in the binary is 1, then it is all negative, but the id we generate is all positive, so the first bit is all 0. / / Machine ID 2-bit 5-bit 32-bit minus 1-bit 31 private long workerId; / / computer room ID 2-bit 5-bit 32-bit minus 1-bit 31 private long datacenterId; / / represents the latest sequence number of multiple id generated in one millisecond 12-bit 4096-1 = 4095 private long sequence; / / set a time initial value 2 ^ 41-1 can almost use 69 years private long twepoch = 15856442688L / / 5-bit machine id private long workerIdBits = 5L; / 5-bit computer room id private long datacenterIdBits = 5L; / / the number of id generated per millisecond 2 to the power of 12 private long sequenceBits = 12L; / / this is a binary operation, that is, 5 bit can only have up to 31 digits, that is, the machine id can only be less than 32 private long maxWorkerId =-1L ^ (- 1L)

Tags: That is time generation machine binary number computer room system algorithm serial number base operation code snowflake content unit meaning method more core Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno OPPO Reno MariaDB Docker Apple vpn