惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

D
DataBreaches.Net
SecWiki News
SecWiki News
博客园_首页
人人都是产品经理
人人都是产品经理
博客园 - 聂微东
P
Palo Alto Networks Blog
V
Vulnerabilities – Threatpost
Project Zero
Project Zero
WordPress大学
WordPress大学
NISL@THU
NISL@THU
酷 壳 – CoolShell
酷 壳 – CoolShell
P
Privacy & Cybersecurity Law Blog
Jina AI
Jina AI
AWS News Blog
AWS News Blog
Scott Helme
Scott Helme
Martin Fowler
Martin Fowler
C
Cybersecurity and Infrastructure Security Agency CISA
Forbes - Security
Forbes - Security
H
Heimdal Security Blog
小众软件
小众软件
I
Intezer
A
Arctic Wolf
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
O
OpenAI News
S
Security Affairs
阮一峰的网络日志
阮一峰的网络日志
Latest news
Latest news
G
GRAHAM CLULEY
Blog — PlanetScale
Blog — PlanetScale
J
Java Code Geeks
N
News and Events Feed by Topic
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
V2EX - 技术
V2EX - 技术
Stack Overflow Blog
Stack Overflow Blog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
L
LINUX DO - 最新话题
博客园 - Franky
P
Proofpoint News Feed
aimingoo的专栏
aimingoo的专栏
博客园 - 司徒正美
P
Proofpoint News Feed
S
Secure Thoughts
Google DeepMind News
Google DeepMind News
Microsoft Security Blog
Microsoft Security Blog
T
The Exploit Database - CXSecurity.com
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
C
CXSECURITY Database RSS Feed - CXSecurity.com
F
Full Disclosure
Security Latest
Security Latest

博客园 - 会长

本地部署DeepSeek并用Python调用 一个用来将数字转换为英文的MySql函数 用C语言实现ElGamal算法 如何用C#代码验证XML文件是否符合DTD规范 如何调试WebBrowser控件中的JS代码 解决Devexpress的RichEditControl控件保存为docx文件后在word里打开字体显示不正确的问题 《水浒传》中的物价 诗词记录 对开发流程优化的建议 如何在HP ProLiant-DL580 Gen9 上安装ESXi NumPy基础 闪存客户端 北京某软件园小公园 MySQL优化技巧 大叔学ML第五:逻辑回归 大叔学ML第四:线性回归正则化 大叔学ML第三:多项式回归 大叔学ML第二:线性回归 大叔学ML第一:梯度下降
Snowflake算法生成Id
会长 · 2024-01-15 · via 博客园 - 会长

网上大部分C#写的都有点乱糟糟,我简化了一下。这个算法总体思想是生成一个64位整数,前42位放从前某特定时间点到当前时间的毫秒数,中间10位放生成id的机器的唯一编码,后12位放顺序号(如果同一毫秒内生成多次,此顺序号可避免产生重复id)

using System;

namespace xxx
{
    /// <summary>
    /// Id 生成类
    /// </summary>
    class Snowflake
    {
        private const string LOCK_OBJ = "76003AEB-E3F9-460A-BD31-D9AE9E7684C0";

        private const int MACHINE_BIT_SIZE = 10; // 机器编号长度10位
        private const int SEQUENCE_BIT_SIZE = 12; // 序号长度12位

        private static Snowflake _snowflake;

        private long _machineNumber; // 机器序号
        private long _timestamp; // 时间戳
        private long _sequence; // 序号

        private Snowflake() { }

        /// <summary>
        /// 设置机器序号
        /// </summary>
        public int MachineNumber
        {
            set { _machineNumber = value; }
        }

        /// <summary>
        /// 得到一个实例
        /// </summary>
        /// <returns></returns>
        public static Snowflake GetInstance()
        {
            if (_snowflake == null)
            {
                lock (LOCK_OBJ)
                {
                    if (_snowflake == null)
                    {
                        _snowflake = new Snowflake();
                    }
                }
            }
            return _snowflake;
        }

        /// <summary>
        /// 产生一个id,由时间戳、机器编码、顺序号组成
        /// </summary>
        /// <returns></returns>
        public long GenerateId(Func<DateTime> GetTime)
        {
            lock (LOCK_OBJ)
            {
                if (_machineNumber > (-1L ^ -1L << MACHINE_BIT_SIZE))
                {
                    throw new ArgumentException("机器编号超出最大值");
                }

                long timestamp = GetTimestamp(GetTime());
                if (timestamp < _timestamp)
                {
                    throw new ArgumentException("时间戳错误");
                }

                if (timestamp == _timestamp)
                {
                    _sequence++;
                    if (_sequence > (-1L ^ -1L << SEQUENCE_BIT_SIZE))
                    {
                        while (true) // 序号已用完,等下一毫秒
                        {
                            timestamp = GetTimestamp(GetTime());
                            if (timestamp > _timestamp)
                            {
                                _sequence = 0;
                                break;
                            }
                        }
                    }
                }
                else
                {
                    _sequence = 0;
                }

                long id = timestamp << (MACHINE_BIT_SIZE + SEQUENCE_BIT_SIZE) 
                    | _machineNumber << SEQUENCE_BIT_SIZE 
                    | _sequence;

                _timestamp = timestamp;

                return id;
            }
        }

        // 当前时间戳
        private long GetTimestamp(DateTime now)
        {
            return (long)(now - new DateTime(2024, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
        }
    }
}

调用:

using System;

namespace xxx
{
    public class IdGenerator
    {
        /// <summary>
        /// 生成Id
        /// </summary>
        /// <returns></returns>
        public static long GenerateId()
        {
            Snowflake sf = Snowflake.GetInstance();
            sf.MachineNumber = YourGetMachineNumberFunction();
            long id = sf.GenerateId(GetTime);
            return id;
        }

        private static DateTime GetTime()
        {
            return YourGetNowTimeFunction();
        }
    }
}