snowflake

package module
v0.0.0-...-7fa830f Latest Latest
Warning

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

Go to latest
Published: Apr 20, 2022 License: GPL-3.0 Imports: 4 Imported by: 1

README

snowflake

Here is the twitter blog about snowflake.

Screen Shot 2022-04-12 at 10 15 06
  • The first bit is an unused assigned bit.
  • The second part consists of a 41-bit timestamp (milliseconds) whose value is the offset of the current time relative to a certain time.
  • The 5 bits of the third and fourth parts represent the data center and worker node, and the max value is
    2^5-1 = 31.
  • The last part consists of 8 bits, which means the length of the serial number generated per millisecond per working node, a maximum of 2^8-1 = 4095 IDs can be generated in the same millisecond.
  • In a distributed environment, a five-bit data center and worker mean that can deploy 31 data centers. Each data center can deploy up to 31 nodes.
  • The binary length of 41 bits is at most 2^41-1 millisecond = 69 years. So the snowflake algorithm can be used for up to 69 years.

Usage

   // Create a node
   n, err := snowflake.NewNode(30, 3)
   if err != nil {
      fmt.Println(err)
   }
    
   // Then, generate a id
   id, err := n.Generate()
   if err != nil {
      fmt.Println(err)
   }

   fmt.Printf("ID: %d\n", id)
   fmt.Printf("String: %s\n", id.String())
   fmt.Printf("Uint64: %d\n", id.UInt64())
   
   fmt.Printf("DecomposeID: %v\n", snowflake.DecomposeID(id))

Test and Benchmarking

  • Test:
  go test -v . 
  • Benchmark:
  go test -bench=. -count=10 -benchtime=2s . 

Attention

  • If you need to handle IDs in Javascript, use a string instead of uint64. Because Javascript's maximum integer value you can safely store 53 bits.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DecomposeID

func DecomposeID(id ID) map[string]uint64

Types

type ID

type ID uint64

func (ID) String

func (f ID) String() string

String returns a string of the snowflake ID

func (ID) UInt64

func (f ID) UInt64() uint64

UInt64 returns a uint64 of the snowflake ID

type Node

type Node struct {

	// Record the time stamp of the last ID
	LastStamp int64

	// ID of the node
	NodeID int64

	// DataCenterID of the node
	DataCenterID int64

	// ID sequence numbers that have been generated in the current millisecond
	// (accumulated from 0)A maximum of 4096 IDs are generated within 1 millisecond
	Sequence int64
	// contains filtered or unexported fields
}

func NewNode

func NewNode(nodeID, dataCenterID int64) (*Node, error)

func (*Node) Generate

func (w *Node) Generate() (ID, error)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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