分布式ID生成算法|雪花算法 Snowflake | Go实现

写在前面

在分布式领域中,不可避免的需要生成一个全局唯一ID。而在近几年的发展中有许多分布式ID生成算法,比较经典的就是 Twitter 的雪花算法(Snowflake Algorithm)。当然国内也有美团的基于snowflake改进的Leaf算法。那么今天我们就来介绍一下雪花算法。

雪花算法

算法来源: 世界上没有完全相同的两片雪花 。所以!雪崩的时候,没有任何一片雪花是相同的!

雪花算法的本质是生成一个64位的 long int 类型的id,可以拆分成一下几个部分:

  • 最高位固定位0。因为第一位为符号位,如果是1那么就是负数了。
  • 接下来的 41 位存储毫秒级时间戳,2^41 大概可以使用69年。
  • 再接来就是10位存储机器码,包括 5 位dataCenterId 和 5 位 workerId。最多可以部署2^10=1024台机器。
  • 最后12位存储序列号。统一毫秒时间戳时,通过这个递增的序列号来区分。即对于同一台机器而言,同一毫秒时间戳下可以生成 2^12=4096 个不重复id

在这里插入图片描述

雪花算法其实是强依赖于时间戳的,因为我们看上面生成的几个数字,我们唯一不可控的就是时间,如果发生了时钟回拨有可能会发生id生成一样了。

所以雪花算法适合那些与时间有强关联的业务 ,比如订单,交易之类的,需要有时间强相关的业务。

生成 ID 流程图

在这里插入图片描述
下面会结合代码讲述详细讲述这张图

代码实现

前置工作

既然是由上述的几个部分组成,那么我们可以先定义几个常量

// 时间戳的 占用位数
timestampBits = 41
// dataCenterId 的占用位数
dataCenterIdBits = 5
// workerId 的占用位数
workerIdBits = 5
// sequence 的占用位数
seqBits = 12

并且定义各个字段的最大值,防止越界

// timestamp 最大值, 相当于 2^41-1 = 2199023255551
timestampMaxValue = -1 ^ (-1 << timestampBits)
// dataCenterId 最大值, 相当于 2^5-1 = 31
dataCenterIdMaxValue = -1 ^ (-1 << dataCenterIdBits)
// workId 最大值, 相当于 2^5-1 = 31
workerIdMaxValue = -1 ^ (-1 << workerIdBits)
// sequence 最大值, 相当于 2^12-1 = 4095
seqMaxValue = -1 ^ (-1 << seqBits)

移动位数

// workId 向左移动12位(seqBits占用位数)因为这12位是sequence占的
workIdShift = 12
// dataCenterId 向左移动17位 (seqBits占用位数 + workId占用位数)
dataCenterIdShift = 17
// timestamp 向左移动22位 (seqBits占用位数 + workId占用位数 + dataCenterId占用位数)
timestampShift = 22

定义雪花生成器的对象,定义上面我们介绍的几个字段即可

type SnowflakeSeqGenerator struct {
	mu           *sync.Mutex
	timestamp    int64
	dataCenterId int64
	workerId     int64
	sequence     int64
}
func NewSnowflakeSeqGenerator(dataCenterId, workId int64) (r *SnowflakeSeqGenerator, err error) {
	if dataCenterId < 0 || dataCenterId > dataCenterIdMaxValue {
		err = fmt.Errorf("dataCenterId should between 0 and %d", dataCenterIdMaxValue-1)
		return
	}

	if workId < 0 || workId > workerIdMaxValue {
		err = fmt.Errorf("workId should between 0 and %d", dataCenterIdMaxValue-1)
		return
	}

	return &SnowflakeSeqGenerator{
		mu:           new(sync.Mutex),
		timestamp:    defaultInitValue - 1,
		dataCenterId: dataCenterId,
		workerId:     workId,
		sequence:     defaultInitValue,
	}, nil
}

具体算法

timestamp存储的是上一次的计算时间,如果当前的时间比上一次的时间还要小,那么说明发生了时钟回拨,那么此时我们不进行生产id,并且记录错误日志。

now := time.Now().UnixMilli()
if S.timestamp > now { // Clock callback
	log.Errorf("Clock moved backwards. Refusing to generate ID, last timestamp is %d, now is %d", S.timestamp, now)
	return ""
}

如果时间相等的话,那就说明这是在 同一毫秒时间戳内生成的 ,那么就进行seq的自旋,在这同一毫秒内最多生成 4095 个。如果超过4095的话,就等下一毫秒。

if S.timestamp == now {
// generate multiple IDs in the same millisecond, incrementing the sequence number to prevent conflicts
	S.sequence = (S.sequence + 1) & seqMaxValue
	if S.sequence == 0 {
		// sequence overflow, waiting for next millisecond
		for now <= S.timestamp {
			now = time.Now().UnixMilli()
		}
	}
}

那么如果是不在同一毫秒内的话,seq直接用初始值就好了

else {
	// initialized sequences are used directly at different millisecond timestamps
	S.sequence = defaultInitValue
}

如果超过了69年,也就是时间戳超过了69年,也不能再继续生成了

tmp := now - epoch
if tmp > timestampMaxValue {
	log.Errorf("epoch should between 0 and %d", timestampMaxValue-1)
	return ""
}

记录这一次的计算时间,这样就可以和下一次的生成的时间做对比了。

S.timestamp = now

timestamp + dataCenterId + workId + sequence 拼凑一起,注意一点是我们最好用字符串输出,因为前端js中的number类型超过53位会溢出的

// combine the parts to generate the final ID and convert the 64-bit binary to decimal digits.
r := (tmp)<<timestampShift |
	(S.dataCenterId << dataCenterIdShift) |
	(S.workerId << workIdShift) |
	(S.sequence)

return fmt.Sprintf("%d", r)

完整代码 & 测试文件

package sequence

import (
	"fmt"
	"sync"
	"time"

	"github.com/seata/seata-go/pkg/util/log"
)

// SnowflakeSeqGenerator snowflake gen ids
// ref: https://en.wikipedia.org/wiki/Snowflake_ID

var (
	// set the beginning time
	epoch = time.Date(2024, time.January, 01, 00, 00, 00, 00, time.UTC).UnixMilli()
)

const (
	// timestamp occupancy bits
	timestampBits = 41
	// dataCenterId occupancy bits
	dataCenterIdBits = 5
	// workerId occupancy bits
	workerIdBits = 5
	// sequence occupancy bits
	seqBits = 12

	// timestamp max value, just like 2^41-1 = 2199023255551
	timestampMaxValue = -1 ^ (-1 << timestampBits)
	// dataCenterId max value, just like 2^5-1 = 31
	dataCenterIdMaxValue = -1 ^ (-1 << dataCenterIdBits)
	// workId max value, just like 2^5-1 = 31
	workerIdMaxValue = -1 ^ (-1 << workerIdBits)
	// sequence max value, just like 2^12-1 = 4095
	seqMaxValue = -1 ^ (-1 << seqBits)

	// number of workId offsets (seqBits)
	workIdShift = 12
	// number of dataCenterId offsets (seqBits + workerIdBits)
	dataCenterIdShift = 17
	// number of timestamp offsets (seqBits + workerIdBits + dataCenterIdBits)
	timestampShift = 22

	defaultInitValue = 0
)

type SnowflakeSeqGenerator struct {
	mu           *sync.Mutex
	timestamp    int64
	dataCenterId int64
	workerId     int64
	sequence     int64
}

// NewSnowflakeSeqGenerator initiates the snowflake generator
func NewSnowflakeSeqGenerator(dataCenterId, workId int64) (r *SnowflakeSeqGenerator, err error) {
	if dataCenterId < 0 || dataCenterId > dataCenterIdMaxValue {
		err = fmt.Errorf("dataCenterId should between 0 and %d", dataCenterIdMaxValue-1)
		return
	}

	if workId < 0 || workId > workerIdMaxValue {
		err = fmt.Errorf("workId should between 0 and %d", dataCenterIdMaxValue-1)
		return
	}

	return &SnowflakeSeqGenerator{
		mu:           new(sync.Mutex),
		timestamp:    defaultInitValue - 1,
		dataCenterId: dataCenterId,
		workerId:     workId,
		sequence:     defaultInitValue,
	}, nil
}

// GenerateId timestamp + dataCenterId + workId + sequence
func (S *SnowflakeSeqGenerator) GenerateId(entity string, ruleName string) string {
	S.mu.Lock()
	defer S.mu.Unlock()

	now := time.Now().UnixMilli()

	if S.timestamp > now { // Clock callback
		log.Errorf("Clock moved backwards. Refusing to generate ID, last timestamp is %d, now is %d", S.timestamp, now)
		return ""
	}

	if S.timestamp == now {
		// generate multiple IDs in the same millisecond, incrementing the sequence number to prevent conflicts
		S.sequence = (S.sequence + 1) & seqMaxValue
		if S.sequence == 0 {
			// sequence overflow, waiting for next millisecond
			for now <= S.timestamp {
				now = time.Now().UnixMilli()
			}
		}
	} else {
		// initialized sequences are used directly at different millisecond timestamps
		S.sequence = defaultInitValue
	}
	tmp := now - epoch
	if tmp > timestampMaxValue {
		log.Errorf("epoch should between 0 and %d", timestampMaxValue-1)
		return ""
	}
	S.timestamp = now

	// combine the parts to generate the final ID and convert the 64-bit binary to decimal digits.
	r := (tmp)<<timestampShift |
		(S.dataCenterId << dataCenterIdShift) |
		(S.workerId << workIdShift) |
		(S.sequence)

	return fmt.Sprintf("%d", r)
}

测试文件

func TestSnowflakeSeqGenerator_GenerateId(t *testing.T) {
	var dataCenterId, workId int64 = 1, 1
	generator, err := NewSnowflakeSeqGenerator(dataCenterId, workId)
	if err != nil {
		t.Error(err)
		return
	}
	var x, y string
	for i := 0; i < 100; i++ {
		y = generator.GenerateId("", "")
		if x == y {
			t.Errorf("x(%s) & y(%s) are the same", x, y)
		}
		x = y
	}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/427331.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

图书管理系统的设计与实现

** &#x1f345;点赞收藏关注 → 私信领取本源代码、数据库&#x1f345; 本人在Java毕业设计领域有多年的经验&#xff0c;陆续会更新更多优质的Java实战项目希望你能有所收获&#xff0c;少走一些弯路。&#x1f345;关注我不迷路&#x1f345;** 一 、设计说明 1.1 课题…

数据结构之树结构(下)

各种各样的大树 平衡二叉树 (AVL树) 普通二叉树存在的问题 左子树全部为空&#xff0c;从形式上看&#xff0c;更像一个单链表 插入速度没有影响 查询速度明显降低&#xff08;因为需要依次比较&#xff09;&#xff0c;不能发挥BST的优势&#xff0c;因为每次还需要比较左子…

Unity 脚本-生命周期常用函数

在Unity中&#xff0c;万物皆是由组件构成的。 右键创建C&#xff03;脚本&#xff0c;拖动脚本到某物体的组件列表。 生命周期相关函数 using System.Collections; using System.Collections.Generic; using UnityEngine;// 必须要继承 MonoBehaviour 才是一个组件 // 类名…

AirPods Pro 2 耳机推送新固件,苹果Find My功能助力产品成长

苹果公司面向 AirPods Pro 2&#xff08;包括 USB-C 和 Lightning 版本&#xff09;&#xff0c;推出了全新的测试版固件更新&#xff0c;版本号为 6E188&#xff0c;高于 12 月份发布的 6B34 固件。 苹果和往常一样&#xff0c;并没有提供详细的更新日志或者说明&#xff0c…

实战——dynamic TP 可视化动态修改线程池参数配置

背景 开发环境 springboot版本号&#xff1a;2.3.12.RELEASE 集成SpringBoot 1、使用apollo动态修改线程池配置 2、使用undertow容器 3、添加maven依赖 <!-- 动态线程池适配器&#xff0c;位置要在undertow依赖前&#xff0c;否则启动报错 --><dependency><g…

用pyinstaller打包python代码为exe可执行文件并在其他电脑运行的方法

本文介绍基于Python语言中的pyinstaller模块&#xff0c;将写好的.py格式的Python代码及其所用到的所有第三方库打包&#xff0c;生成.exe格式的可执行文件&#xff0c;从而方便地在其他环境、其他电脑中直接执行这一可执行文件的方法。 有时&#xff0c;我们希望将自己电脑上的…

【外汇天眼】外汇交易风险预警:吊销牌照与高风险平台一览

监管信息早知道&#xff01;外汇天眼将每周定期公布监管牌照状态发生变化的交易商&#xff0c;以供投资者参考&#xff0c;规避投资风险。如果平台天眼评分过高&#xff0c;建议投资者谨慎选择&#xff0c;因为在外汇天眼评分高不代表平台没问题&#xff01; 以下是监管牌照发生…

错误: 找不到或无法加载主类 com.zql.springbootTest.SpringbootTestApplication

首先查看application.properties是否出现问题 然后可以尝试 maven install

从基础到高级:Go 语言中 Base32 编码的全面指南

从基础到高级&#xff1a;Go 语言中 Base32 编码的全面指南 引言基础知识base32 编码简介为什么选择 base32 encoding/base32 包概览包的结构和主要类型基本概念 实战教程开始使用 encoding/base32设置开发环境基本的 base32 编码示例解码示例 深入编码细节使用不同的编码表 错…

重保利器,企业安全巡查!亚信安全外部攻击面管理服务可以试用啦

重大安全保障期间 信息系统的稳定与安全至关重要 守在明&#xff0c;攻在暗 传统的防护多始于已知资产的保护 而未知影子资产 则很可能成为攻击者长驱直入的攻击路径 号外号外&#xff01; 亚信安全“外部攻击面管理服务” 即日起&#xff0c;面向新用户 限时试用&…

上门家政服务APP如何开发?看这一篇文章就够了

当下生活节奏快&#xff0c;工作压力大&#xff0c;人们往往无暇处理家务。上门家政APP因此成为刚需&#xff0c;提供便捷、高效的家政服务&#xff0c;满足用户各类需求&#xff0c;解放时间精力。得益于其透明的价格、严格审核的服务人员及用户评价系统&#xff0c;上门家政A…

为什么要学习三维GIS开发?从技术层面告诉你答案

大家都知道GIS开发属于GIS行业中就业薪资较高的岗位&#xff0c;并且测绘、遥感以及城规等相关专业的毕业生纷纷转行做webgis开发。 那么&#xff0c;今天小编从技术层面探讨一下&#xff0c;为什么建议大家不要仅仅停留在webgis&#xff0c;而要继续往前学习三维GIS开发&…

PclSharp1.12.0--均匀采样

一、均匀采样 均匀采样的原理类似于体素化网格采样方法&#xff0c;同样是将点云空间进行划分&#xff0c;不过是以半径r的球体&#xff0c;在当前球体所有点中选择距离球体中心最近的点替代所有点&#xff0c;注意&#xff0c;此时点的位置是不发生移动的。 球体半径选取越大…

yolov8-更换卷积模块-ContextGuidedBlock_Down

源码解读 class ContextGuidedBlock_Down(nn.Module):"""the size of feature map divided 2, (H,W,C)---->(H/2, W/2, 2C)"""def __init__(self, nIn, dilation_rate2, reduction16):"""args:nIn: the channel of input fea…

项目解决方案: 实时视频拼接方案介绍(下)

目 录 1.实时视频拼接概述 2.适用场景 3.系统介绍 4.拼接方案介绍 4.1基于4K摄像机的拼接方案 4.2采用1080P平台3.0 横向拼接 4.3纵横兼顾&#xff0c;竖屏拼接 5.前端选择及架设 5.1前端架设原则 5.1.1安装示意图 5.1.2安装调试基本原则 5.2摄像机及支架 5.…

深入分析Android运行时环境ART:原理、特点与优化策略

摘要 随着移动互联网的快速发展&#xff0c;智能手机的性能和功能日益强大&#xff0c;其中Android操作系统因其开放性和灵活性而占据主导地位。Android运行时环境&#xff08;ART&#xff09;作为执行应用程序代码的关键组件&#xff0c;在系统性能和用户体验方面起着至关重要…

三维可视化技术在设备管理系统中的应用

随着科技的进步&#xff0c;传统的设备管理方法已经不能满足现代企业的需求。为了更高效地管理资产&#xff0c;设备管理系统开始采用三维可视化动态技术。这种技术不仅能够帮助用户快速找到相应的设备&#xff0c;还能够展示设备的现场位置、所处环境、关联设备以及设备参数等…

Project_Euler-12 题解

Project_Euler-12 题解 题目 思路 我们可以从小到大枚举每一个三角形数&#xff0c;然后计算他们的约数个数&#xff0c;从而得到结果。 代码 #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include <time.h&…

alibabacloud学习笔记07(小滴课堂)

讲解Sentinel自定义异常降级-新旧版本差异 讲解新版Sentinel自定义异常数据开发实战 如果我们都使用原生的报错&#xff0c;我们就无法得到具体的报错信息。 所以我们要自定义异常返回的数据提示&#xff1a; 实现BlockExceptionHandler并且重写handle方法&#xff1a; 使用F…

推荐我最近刚发现的5款实用软件

​ 我喜欢发现和分享一些好用的软件&#xff0c;我觉得它们可以让我们的工作和生活更加轻松和快乐。今天给大家介绍五款我最近发现的软件。 1.桌面工具——PowerToys ​ PowerToys是一款由微软开发的免费开源软件&#xff0c;旨在为Windows 10用户提供更多的自定义和增强功能…