当前位置:网站首页>Snowflake ID (go Implementation)
Snowflake ID (go Implementation)
2022-07-27 16:27:00 【Wang Hao】
snow ID The implementation of the
When I was working on a project before, I encountered , Let's have a deeper understanding today .
List of articles
Preface
snow ID The most open-source one by Twitter is globally unique ID Generation algorithm of , Incremental 、 Global uniqueness and other characteristics .
One 、 snow ID The role of ?
- Global uniqueness
For multiple machines , Generate multiple non repeating messages in milliseconds ID - Incremental
Generated snowflakes ID With incremental , It can speed up the query . - High availability
Multithreading support , Distributed system architecture
Two 、 snow ID Principle
- The highest bit is the sign bit , Generated ID Always positive , So always for 0.
- 41 Time series of bits , To the millisecond level ,41 The length of bits can be used 69 year , You can use this feature to sort
- Set the representation of the machine code , It can support distributed systems
- 12 Bit count encoding , It can support multiple different in milliseconds ID Generate .

3、 ... and 、 snow ID Code implementation of (Go Language )
Some parts about the principle are commented in the code .
There are also some requirements for snowflakes ID Modification of algorithm
package main
import (
"fmt"
"sync"
"time"
)
// Support 2 ^ 8 - 1 Taiwan machine
// Every millisecond supports 2 ^ 9 - 1 Different id
const (
workerIdBitsMoveLen = uint(8)
maxWorkerId = int64(-1 ^ (-1 << workerIdBitsMoveLen))
timerIdBitsMoveLen = uint(17)
maxNumId = int64(-1 ^ (-1 << 9))
)
// Define a woker The basic parameters needed by the work node
type Worker1 struct {
mu sync.Mutex // Add mutex Ensure concurrency security
workerId int64 // Machine coding
timestamp int64 // Record timestamp
number int64 // The current MS has generated id Serial number ( from 0 Start accumulating ) 1 At most in milliseconds 4096 individual ID
}
// initialization ID Generating structures
// workerId The number of the machine
func NewWorker1(workerId int64) *Worker1 {
if workerId > maxWorkerId {
panic("workerId Can't be greater than the maximum ")
}
return &Worker1{
workerId: workerId,timestamp: 0, number: 0}
}
// Generate id The method of is used to generate unique id
func (w *Worker1) GetId() int64 {
epoch := int64(1613811738) // Set to the timestamp of last year and today ... Because the number of digits changed , It can't be used up for hundreds of years ,, You can actually set the launch date
w.mu.Lock()
defer w.mu.Unlock()
now := time.Now().UnixMilli() // Get the current timestamp
if now < w.timestamp {
// When the machine has clock back dialing error
panic("Clock moved backwards. Refusing to generate id for %d milliseconds")
}
if w.timestamp == now {
w.number++
if w.number > maxNumId {
// Here is the largest node ID, Probably 2^9-1 511 strip ,
for now <= w.timestamp {
now = time.Now().UnixMilli()
}
}
} else {
w.number = 0
w.timestamp = now // The last time the machine generated ID Update the time of to the current time
}
ID := int64((now-epoch)<< timerIdBitsMoveLen | (w.workerId << workerIdBitsMoveLen) | (w.number))
return ID
}
func testGetId() {
worker := NewWorker1(55)
arr := make([]int64,0 ,100)
for i := 0; i < 100; i++ {
arr = append(arr, worker.GetId())
}
fmt.Printf("%+v\n", arr)
}
func main() {
testGetId()
}
Four 、 snow ID The shortcomings of
For example, it will cause some problems, such as machine timestamp callback ID Repetitive questions
边栏推荐
猜你喜欢

TP5 paging some small points

JSP基础

The new JMeter function assistant is not under the options menu - in the toolbar

MySQL high version report SQL_ mode=only_ full_ group_ By exception

Determine the exact type of data

Mysql5.7 master-slave hot standby settings on CentOS

webRTC中的coturn服务安装

DEX and AMMS of DFI security

C channel simply implements the publishing and subscription of message queue

新版jmeter函数助手不在选项菜单下-在工具栏中
随机推荐
2.2 basic elements of JMeter
Coturn service installation in webrtc
Rotate string left
Leetcode234 question - simple method to judge palindrome linked list
For enterprise operation and maintenance security, use the cloud housekeeper fortress machine!
Two methods of generating excel table with PHP
matlab legend用法
Example of the task submitted by the Flink packer
DEX and AMMS of DFI security
Addition of large numbers
知网、万方数据库免费下载论文------比连接学校内网速度快数倍不止(有的学校万方数据库不支持下载)
google chrome revercecaptcha广告屏蔽
Cron expression use
The difference and use between get request and post request
Sudden! 28 Chinese entities including Hikvision / Dahua / Shangtang / Kuangshi / ITU / iFLYTEK have been blacklisted by the United States
C channel simply implements the publishing and subscription of message queue
4-digit random data
MySQL index
Duplicate numbers in array
Redis简介与使用