snowflake

package module
v1.0.5 Latest Latest
Warning

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

Go to latest
Published: Aug 26, 2024 License: MIT Imports: 2 Imported by: 1 module, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

snowflake

雪花算法,用于生成分布式数据库中的主键。能保证全局唯一性、趋势递增和信息安全。

原理

使用

  1. 安装依赖
go get -u github.com/zhanglp0129/snowflake
  1. 创建雪花算法配置
startTime, _ := time.Parse("2006-01-02 15:04:05", "2024-08-14 00:00:00")
cfg := snowflake.NewDefaultConfigWithStartTime(startTime)
  1. 创建工作节点
worker, err := snowflake.NewWorker(cfg, 0)
  1. 生成id
id, err := worker.GenerateId()

LICENSE

MIT

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// DefaultConfig 雪花算法默认配置
	DefaultConfig = SnowFlakeConfig{
		StartTimestamp: 0,
		TimestampBits:  41,
		MachineIdBits:  10,
		SeqBits:        12,
	}
)

Functions

func GetMachineId added in v1.0.4

func GetMachineId(c SnowFlakeConfig, id int64) (int64, error)

GetMachineId 获取机器码

Types

type SnowFlakeConfig

type SnowFlakeConfig struct {
	// 起始时间戳,单位为毫秒,默认为0,即1970-01-01 00:00:00.000
	StartTimestamp int64
	// 时间戳位数,默认为41
	TimestampBits uint8
	// 机器码位数,默认为10
	MachineIdBits uint8
	// 序列号位数,默认为12
	SeqBits uint8
}

SnowFlakeConfig 雪花

func NewDefaultConfigWithStartTime added in v1.0.3

func NewDefaultConfigWithStartTime(startTime time.Time) SnowFlakeConfig

NewDefaultConfigWithStartTime 创建一个雪花算法默认配置,并指定起始时间

func (*SnowFlakeConfig) SetStartTime

func (c *SnowFlakeConfig) SetStartTime(startTime time.Time)

SetStartTime 设置起始时间

type SnowflakeError added in v1.0.5

type SnowflakeError string
const (
	BitsSumError     SnowflakeError = "the sum of bits error, must be 63"
	MachineIdIllegal SnowflakeError = "machine id is illegal"
	TimestampIllegal SnowflakeError = "timestamp is illegal"
	SeqIllegal       SnowflakeError = "sequence is illegal"
)

func (SnowflakeError) Error added in v1.0.5

func (e SnowflakeError) Error() string

type Worker

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

Worker 工作节点

func (*Worker) GenerateId

func (w *Worker) GenerateId() (int64, error)

GenerateId 生成雪花id

type WorkerInterface added in v1.0.4

type WorkerInterface interface {
	GenerateId() (int64, error)
}

func NewWorker

func NewWorker(c SnowFlakeConfig, machineId int64) (WorkerInterface, error)

NewWorker 创建一个雪花算法的工作节点

Jump to

Keyboard shortcuts

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