snowflake

package module
v0.0.0-...-883c008 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2020 License: Apache-2.0 Imports: 4 Imported by: 0

README

snowflake

==============

snowflake is a distributed unique ID generator inspired by Twitter's Snowflake.

A snowflake ID is composed of

41 bits for time in units of 10 msec
10 bits for a instance id
12 bits for a sequence number

Quick Started

Installation

$ go get -u github.com/Yu-33/snowflake

Usage

package man

import (
	"fmt"
	
	"github.com/Yu-33/snowflake"
)

func main() {
    // create a new worker
    instanceID := int64(1)
    worker, err := snowflake.New(instanceID)
    if err != nil {
        fmt.Printf("new snowflake fail: %v\n", err)
        return
    }
    
    // take id
    for i := 0; i < 8; i++ {
        id, err := worker.Next()
        if err != nil {
            fmt.Printf("generate id fail: %v\n", err)
            return
        }
        fmt.Printf("New ID: %d\n", id)
    }
	
    // take batch
    ids, err := worker.Batch(100)
    if err != nil {
        fmt.Printf("generate ids fail: %v\n", err)
        return
    }
    fmt.Println(ids)
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Decompose

func Decompose(id int64) (timestamp int64, instanceID int64, sequenceID int64)

Decompose decompose id to timestamp instance id and sequence id

Types

type Snowflake

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

Snowflake for implements algorithm of snowflake

func New

func New(instanceID int64) (*Snowflake, error)

New return a new SnowFlake

func (*Snowflake) Batch

func (sf *Snowflake) Batch(num int) ([]int64, error)

Batch return multiple ids at once

func (*Snowflake) Next

func (sf *Snowflake) Next() (int64, error)

Next return a unique id with thread safe

Jump to

Keyboard shortcuts

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