gsnowflake

package
v1.0.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 27, 2023 License: MulanPSL-2.0 Imports: 6 Imported by: 1

Documentation

Overview

snowflake is a distributed unique ID generator inspired by Twitter's snowflake. snowflake focuses on lifetime and performance on many host/core environment. So it has a different bit assignment from snowflake. A snowflake ID is composed of

Package sonyflake implements Snowflake, a distributed unique ID generator inspired by Twitter's Snowflake.

A Snowflake 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

Index

Constants

View Source
const (
	BitLenTime      = 39                               // bit length of time
	BitLenSequence  = 8                                // bit length of sequence number
	BitLenMachineID = 63 - BitLenTime - BitLenSequence // bit length of machine id
)

These constants are the bit lengths of Snowflake ID parts.

Variables

This section is empty.

Functions

func Decompose

func Decompose(id uint64) map[string]uint64

Decompose returns a set of Snowflake ID parts.

func GetId

func GetId() uint64

Types

type Settings

type Settings struct {
	StartTime      time.Time
	MachineID      func() (uint16, error)
	CheckMachineID func(uint16) bool
}

Settings configures Snowflake:

StartTime is the time since which the Snowflake time is defined as the elapsed time. If StartTime is 0, the start time of the Snowflake is set to "2014-09-01 00:00:00 +0000 UTC". If StartTime is ahead of the current time, Snowflake is not created.

MachineID returns the unique ID of the Snowflake instance. If MachineID returns an error, Snowflake 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, Snowflake is not created. If CheckMachineID is nil, no validation is done.

type Snowflake

type Snowflake struct {
	// contains filtered or unexported fields
}

Snowflake is a distributed unique ID generator.

func GetSnowflake

func GetSnowflake() *Snowflake

func NewSnowflake

func NewSnowflake(st Settings) *Snowflake

NewSnowflake returns a new Snowflake configured with the given Settings. NewSnowflake returns nil in the following cases: - Settings.StartTime is ahead of the current time. - Settings.MachineID returns an error. - Settings.CheckMachineID returns false.

func (*Snowflake) NextID

func (sf *Snowflake) NextID() (uint64, error)

NextID generates a next unique ID. After the Snowflake time overflows, NextID returns an error.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL