uuid

package
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Feb 25, 2021 License: BSD-3-Clause Imports: 19 Imported by: 0

README

uuid

分布式ID生成

Usage

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

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

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

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

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

发号器算法
  • 假设算法是一个发号器
  • 分布式环境下每个app向发号器申请领取一个号段
  • app内部使用这个号段向业务层分配ID
  • 号段分配完以后,再向发号器申请下一个号段

发号器依赖存储组件,存储组件内部维持一个counter和step,发号器每次收到申请将此counter自增

本包提供两种存储选择,etcd和redis

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

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

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")

Functions

func Init

func Init(workerId uint16, addr, key string)

func MustCreateGUID

func MustCreateGUID() string

func NextID

func NextID() int64

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

func NextUUID

func NextUUID() int64

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

Types

type EtcdStore

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

func (*EtcdStore) Close

func (s *EtcdStore) Close()

func (*EtcdStore) Init added in v1.0.2

func (s *EtcdStore) Init() error

func (*EtcdStore) MustNext added in v1.0.2

func (s *EtcdStore) MustNext() int64

func (*EtcdStore) Next added in v1.0.2

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

type KeyValue added in v1.0.2

type KeyValue struct {
	// key is the key in bytes. An empty key is not allowed.
	Key string `json:"key,omitempty"`
	// create_revision is the revision of last creation on this key.
	CreateRevision string `json:"create_revision,omitempty"`
	// mod_revision is the revision of last modification on this key.
	ModRevision string `json:"mod_revision,omitempty"`
	// version is the version of the key. A deletion resets
	// the version to zero and any modification of the key
	// increases its version.
	Version string `json:"version,omitempty"`
	// value is the value held by the key, in bytes.
	Value string `json:"value,omitempty"`
	// lease is the ID of the lease that attached to key.
	// When the attached lease expires, the key will be deleted.
	// If lease is 0, then no lease is attached to the key.
	Lease string `json:"lease,omitempty"`
}

type PutResponse added in v1.0.2

type PutResponse struct {
	Header *ResponseHeader `json:"header,omitempty"`
	// if prev_kv is set in the request, the previous key-value pair will be returned.
	PrevKv *KeyValue `json:"prev_kv,omitempty"`
}

type RedisStore

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

func (*RedisStore) Close

func (s *RedisStore) Close()

func (*RedisStore) Init added in v1.0.2

func (s *RedisStore) Init() error

func (*RedisStore) MustNext added in v1.0.2

func (s *RedisStore) MustNext() int64

func (*RedisStore) Next added in v1.0.2

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

type ResponseHeader added in v1.0.2

type ResponseHeader struct {
	// cluster_id is the ID of the cluster which sent the response.
	ClusterId string `json:"cluster_id,omitempty"`
	// member_id is the ID of the member which sent the response.
	MemberId string `json:"member_id,omitempty"`
	// revision is the key-value store revision when the request was applied.
	// For watch progress responses, the header.revision indicates progress. All future events
	// recieved in this stream are guaranteed to have a higher revision number than the
	// header.revision number.
	Revision string `json:"revision,omitempty"`
	// raft_term is the raft term when the request was applied.
	RaftTerm string `json:"raft_term,omitempty"`
}

type SequenceID

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

func NewSequenceID

func NewSequenceID(store Storage, step int32) *SequenceID

func (*SequenceID) Init

func (s *SequenceID) Init() (err error)

func (*SequenceID) Next

func (s *SequenceID) Next() int64

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 {
	Init() error
	Next() (int64, error)
	MustNext() int64
	Close()
}

func NewEtcdStore

func NewEtcdStore(addr, key string) Storage

func NewRedisStore

func NewRedisStore(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