uuid

package
v1.3.22 Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2021 License: BSD-3-Clause Imports: 20 Imported by: 0

README

uuid

分布式ID生成

Usage

// 初始化传入workerID, etcd地址,和命名空间前缀
uuid.Init(1001, "localhost:2379", "/keyspace/")

// 返回一个ID,使用发号器算法,可用于角色、工会ID
id := NextID()

// 返回一个UUID,使用雪花算法,可用于事件行为、日志ID,通常值比较大
uuid := NextUUID()

雪花算法
时间戳 WorkerID SeqID
  • 把一个64位的整数分成3个区间,分别用于时间戳workerIDseqID
  • 时间戳代表时间单元需要一直递增,不同的时间单元实现有毫秒、秒、厘秒等,这里依赖时钟不回调;
  • workerID用来标识分布式环境下的每个service;
  • seqID在一个时间单元内持续自增,如果在单个时间单元内seqID溢出了,需要sleep等待进入下一个时间单元;

不同的雪花算法实现的差异主要集中在3个区间的分配,和workerID自动还是手动分配上。

  • sony的实现 https://github.com/sony/sonyflake
  • 百度的实现 https://github.com/baidu/uid-generator
  • 美团的实现 https://github.com/Meituan-Dianping/Leaf
发号器算法
  • 算法把一个64位的整数按step划分为N个号段;
  • 每个service向发号器申请领取一个代表号段的counter;
  • service内部使用这个号段向业务层分配ID
  • service重启或者号段分配完,向发号器申请下一个号段

发号器依赖存储组件,对存储组件的需求是能实现整数自增

本包提供多种存储选择,etcd、redis和mongodb

  • etcd使用单个key的revision来实现自增
  • redis使用incr命令实现自增
  • mongodb使用findOneAndUpdate

Documentation

Overview

This package provides immutable UUID structs and the functions NewV3, NewV4, NewV5 and Parse() for generating versions 3, 4 and 5 UUIDs as specified in RFC 4122.

Copyright (C) 2011 by Krzysztof Kowalik <chris@nu7hat.ch>

Index

Constants

View Source
const (
	SequenceBits   = 10
	MachineIDBits  = 16
	TimestampShift = SequenceBits + MachineIDBits
	TimeUnitBits   = 63 - TimestampShift

	Twepoch = 1577836800_000_000_000 // custom epoch in nanosecond, (2020-01-01 00:00:00 UTC)
)
View Source
const (
	ReservedNCS       byte = 0x80
	ReservedRFC4122   byte = 0x40
	ReservedMicrosoft byte = 0x20
	ReservedFuture    byte = 0x00
)

The UUID reserved variants.

View Source
const (
	DefaultSeqStep = 2000 // 默认每个counter分配2000个号
)
View Source
const OpTimeout = 300

DB超时

View Source
const (
	UUIDCollection = "uuid"
)

Variables

View Source
var (
	NamespaceDNS, _  = ParseHex("6ba7b810-9dad-11d1-80b4-00c04fd430c8")
	NamespaceURL, _  = ParseHex("6ba7b811-9dad-11d1-80b4-00c04fd430c8")
	NamespaceOID, _  = ParseHex("6ba7b812-9dad-11d1-80b4-00c04fd430c8")
	NamespaceX500, _ = ParseHex("6ba7b814-9dad-11d1-80b4-00c04fd430c8")
)

The following standard UUIDs are for use with NewV3() or NewV5().

View Source
var (
	ErrCannotPutEtcd = errors.New("cannot put counter to etcd")
)
View Source
var ErrIDOutOfRange = errors.New("ID out of range")
View Source
var ErrNoRowsAffected = errors.New("no rows affected")

Functions

func Init

func Init(workerId uint16, store Storage)

func MustCreateGUID

func MustCreateGUID() string

生成GUID

func NextID

func NextID() int64

生成依赖存储,可用于角色ID

func NextUUID

func NextUUID() int64

生成的值与时钟有关,通常值比较大,可用于日志ID

Types

type Counter

type Counter struct {
	Label string `bson:"label"` // 识别符
	Count int64  `bson:"count"` // 计数器
	Step  int32  `bson:"step"`  //
}

计数器

type EtcdStore

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

使用etcd的key的版本号自增实现

func (*EtcdStore) Close

func (s *EtcdStore) Close() error

func (*EtcdStore) Incr

func (s *EtcdStore) Incr() (int64, error)

type IDGenerator added in v1.2.1

type IDGenerator interface {
	Next() (int64, error)
}

type MongoStore

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

func (*MongoStore) Close

func (s *MongoStore) Close() error

func (*MongoStore) Incr

func (s *MongoStore) Incr() (int64, error)

type MySQLStore

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

func (*MySQLStore) Close

func (s *MySQLStore) Close() error

func (*MySQLStore) Incr

func (s *MySQLStore) Incr() (int64, error)

type RedisStore

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

使用redis INCR命令实现

func (*RedisStore) Close

func (s *RedisStore) Close() error

func (*RedisStore) Incr

func (s *RedisStore) Incr() (int64, error)

type SeqID

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

使用发号器算法的uuid生成器 1. 算法把一个64位的整数按step范围划分为N个号段; 2. service从发号器拿到号段后才可分配此号段内的ID; 3. 发号器依赖存储(etcd, redis)把当前待分配号段持续自增;

func NewSeqID

func NewSeqID(store Storage, step int32) *SeqID

func (*SeqID) Init

func (s *SeqID) Init() error

func (*SeqID) MustNext

func (s *SeqID) MustNext() int64

func (*SeqID) Next

func (s *SeqID) Next() (int64, error)

type SnowFlake

type SnowFlake struct {
	sync.Mutex
	// contains filtered or unexported fields
}

雪花算法生成uuid

func NewSnowFlake

func NewSnowFlake(machineId uint16) *SnowFlake

func (*SnowFlake) Next

func (sf *SnowFlake) Next() int64

type Storage

type Storage interface {
	Incr() (int64, error)
	Close() error
}

Storage表示一个存储组件,维持一个持续递增(不一定连续)的counter

func NewEtcdStore

func NewEtcdStore(ctx context.Context, cli *clientv3.Client, key string) Storage

func NewMongoDBStore

func NewMongoDBStore(ctx context.Context, uri, db, label string, step int32) Storage

func NewMySQLStore

func NewMySQLStore(ctx context.Context, dsn, table, label string, step int) Storage

func NewRedisStore

func NewRedisStore(ctx context.Context, addr, key string) Storage

type UUID

type UUID [16]byte

A UUID representation compliant with specification in RFC 4122 document.

func NewV3

func NewV3(ns *UUID, name []byte) (u *UUID, err error)

Generate a UUID based on the MD5 hash of a namespace identifier and a name.

func NewV4

func NewV4() (u *UUID, err error)

Generate a random UUID.

func NewV5

func NewV5(ns *UUID, name []byte) (u *UUID, err error)

Generate a UUID based on the SHA-1 hash of a namespace identifier and a name.

func Parse

func Parse(b []byte) (u *UUID, err error)

Parse creates a UUID object from given bytes slice.

func ParseHex

func ParseHex(s string) (u *UUID, err error)

ParseHex creates a UUID object from given hex string representation. Function accepts UUID string in following formats:

uuid.ParseHex("6ba7b814-9dad-11d1-80b4-00c04fd430c8")
uuid.ParseHex("{6ba7b814-9dad-11d1-80b4-00c04fd430c8}")
uuid.ParseHex("urn:uuid:6ba7b814-9dad-11d1-80b4-00c04fd430c8")

func (*UUID) String

func (u *UUID) String() string

Returns unparsed version of the generated UUID sequence.

func (*UUID) Variant

func (u *UUID) Variant() byte

Variant returns the UUID Variant, which determines the internal layout of the UUID. This will be one of the constants: RESERVED_NCS, RFC_4122, RESERVED_MICROSOFT, RESERVED_FUTURE.

func (*UUID) Version

func (u *UUID) Version() uint

Version returns a version number of the algorithm used to generate the UUID sequence.

Jump to

Keyboard shortcuts

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