snowflake

package
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Aug 31, 2021 License: GPL-3.0 Imports: 4 Imported by: 0

Documentation

Index

Constants

View Source
const (
	TimestampLength = 41
	MachineIDLength = 10
	SequenceLength  = 12
	MaxSequence     = 1<<SequenceLength - 1
	MaxTimestamp    = 1<<TimestampLength - 1
	MaxMachineID    = 1<<MachineIDLength - 1
)

These constants are the bit lengths of snowflake ID parts.

Variables

This section is empty.

Functions

func AtomicResolver

func AtomicResolver(ms int64) (uint16, error)

AtomicResolver define as atomic sequence resolver, base on standard sync/atomic.

func ID

func ID() uint64

ID use ID to generate snowflake id and it will ignore error. if you want error info, you need use NextID method. This function is thread safe.

func NextID

func NextID() (uint64, error)

NextID use NextID to generate snowflake id and return an error. This function is thread safe.

func PrivateIPToMachineID

func PrivateIPToMachineID() uint16

PrivateIPToMachineID convert private ip to machine id.

func SetMachineID

func SetMachineID(m uint16)

SetMachineID specify the machine ID. It will panic when machineid > max limit for 2^10-1. This function is thread-unsafe, recommended you call him in the main function.

func SetSequenceResolver

func SetSequenceResolver(seq SequenceResolver)

SetSequenceResolver set an custom sequence resolver. This function is thread-unsafe, recommended you call him in the main function.

func SetStartTime

func SetStartTime(s time.Time)

SetStartTime set the start time for snowflake algorithm.

It will panic when:

s IsZero
s > current millisecond
current millisecond - s > 2^41(69 years).

This function is thread-unsafe, recommended you call him in the main function.

Types

type SID

type SID struct {
	Sequence  uint64
	MachineID uint64
	Timestamp uint64
	ID        uint64
}

SID snowflake id

func ParseID

func ParseID(id uint64) SID

ParseID parse snowflake it to SID struct.

func (*SID) GenerateTime

func (id *SID) GenerateTime() time.Time

GenerateTime snowflake generate at, return a UTC time.

type SequenceResolver

type SequenceResolver func(ms int64) (uint16, error)

SequenceResolver the snowflake sequence resolver.

When you want use the snowflake algorithm to generate unique ID, You must ensure: The sequence-number generated in the same millisecond of the same node is unique. Based on this, we create this interface provide following reslover:

AtomicResolver : base sync/atomic (by default).

Jump to

Keyboard shortcuts

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