This file implements SonyFlake distributed id generate algorithm and some extensions. SonyFlake
SonyFlake is a distributed unique ID generator inspired by Twitter's Snowflake.
SonyFlake focuses on lifetime and performance on many host/core environment. So it has a different bit assignment from Snowflake. A SonyFlake ID is composed of
- 39 bits for time in units of 10 msec
- 8 bits for a sequence number
- 16 bits for a machine id
As a result, SonyFlake has the following advantages and disadvantages:
- The lifetime (174 years) is longer than that of Snowflake (69 years)
- It can work in more distributed machines (216) than Snowflake (210)
- It can generate 2^8 IDs per 10 msec at most in a single machine/thread (slower than Snowflake)
However, if you want more generation rate in a single host, you can easily run multiple SonyFlake ID generators concurrently using goroutines.
Usage
The function NewSonyFlake creates a new SonyFlake instance.
You can configure SonyFlake by the struct Settings:
Install
Add the following to your Cargo.toml:
[]
= "0.1"
Quickstart
- Fallible SonyFlake
Sonyflakemay fail to generate a unique ID when we callnext_idif time overflows.use ; use Utc; - Infallible SonyFlake
InfallibleSonyFlakewill always generate a unique ID when we callnext_idif time overflow happens, it will refresh thestart_timeto the current time.use ; use Utc; - Custom machine ID and machine ID checker
use ; use Utc; ;
-
StartTime is the time since which the SonyFlake time is defined as the elapsed time. If StartTime is 0, the start time of the SonyFlake is set to "2021-08-06 00:00:00 +0000 UTC". If StartTime is ahead of the current time, SonyFlake is not created.
-
MachineID returns the unique ID of the SonyFlake instance. If MachineID returns an error, SonyFlake is not created. If MachineID is nil, default MachineID is used. Default MachineID returns the lower 16 bits of the private IP address.
-
CheckMachineID validates the uniqueness of the machine ID. If CheckMachineID returns false, SonyFlake is not created. If CheckMachineID is nil, no validation is done.
In order to get a new unique ID, you just have to call the method NextID.
NextID can continue to generate IDs for about 174 years from StartTime.
But after the SonyFlake time is over the limit, NextID returns an error. Or, you can use InfallibleSonyFlake, InfallibleSonyFlake will always generate a unique ID when we call next_id if time overflow happens, it will refresh the start_time to the current time.