In distributed system, we generally split some businesses with large data volume, such as order table and user table. There’s too much data to fit on one table. It’s going to be categorized and tabulated. But once it comes to the sub-table, it will be extended to the generation of unique primary key ID in distributed system, never migrate data and avoid hot topics in the article requires the unique ID feature.

There are many types of distributed ID generation algorithms, and Twitter’s SnowFlake is a classic one.

Php-fpm, shell-CLI, and php-s 127.0.0.1:80 are supported by default to generate globally unique ids. The default operating environment is php-fPM, shell-CLI, php-s 127.0.0.1:80

Twitter edition SnowFlake

The SnowFlake algorithm generates 64-bit positive binary integers, which are then converted to base 10 numbers. The 64-bit binary number consists of the following parts:

Optimized post-Snowflake version

Transformation of Snowflake algorithm based on Twitter, distributed global unique ID generator, composed of < millisecond timestamp + machine IP + process ID + serial number >

The value contains a maximum of 64 bits. The meanings of each bit are as follows:

  • 1 aDon’t have to. The highest digit 1 in binary is negative, but the iD we generate is usually an integer, so the highest digit is always 0
  • 41Used to record time stamps (milliseconds)
    • 41 bits can be representedA number,
    • If used only to represent positive integers (positive numbers include 0 in computers), they can range from 0 to, minus 1 because the range of representable values starts at 0, not 1.
    • That means 41 bitsMilliseconds, converted to yearsyears
  • 10The machine IP is 10 bits lower and can support up to 1023 machine nodes
  • 10The current process id,10 bits in length, supports a maximum of 1023 machine processes
  • twoCounting serial number, serial number is sequence increment ID, can support the same process on the same node to generate four ID serial number in the same millisecond

advantages

1. This scheme can generate 4,096,000 IDS per second, with fast performance. 2Copy the code

disadvantages

1. It depends on the clock of the machine. If the clock of the server is dialed back, duplicate ids will be generatedCopy the code

practical

Composer require webergiles/ Favorites use webergiles \Favorites\Snowflake; // Generate a globally unique IDecho Snowflake::uniqueId();

Copy the code