博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C# 实现 Snowflake算法 ID生成
阅读量:6157 次
发布时间:2019-06-21

本文共 5307 字,大约阅读时间需要 17 分钟。

///     /// 动态生产有规律的ID Snowflake算法是Twitter的工程师为实现递增而不重复的ID实现的    /// http://blog.csdn.net/w200221626/article/details/52064976         /// C# 实现 Snowflake算法     ///     public class Snowflake    {        private static long machineId;//机器ID        private static long datacenterId = 0L;//数据ID        private static long sequence = 0L;//计数从零开始        private static long twepoch = 687888001020L; //唯一时间随机量        private static long machineIdBits = 5L; //机器码字节数        private static long datacenterIdBits = 5L;//数据字节数        public static long maxMachineId = -1L ^ -1L << (int)machineIdBits; //最大机器ID        private static long maxDatacenterId = -1L ^ (-1L << (int)datacenterIdBits);//最大数据ID        private static long sequenceBits = 12L; //计数器字节数,12个字节用来保存计数码                private static long machineIdShift = sequenceBits; //机器码数据左移位数,就是后面计数器占用的位数        private static long datacenterIdShift = sequenceBits + machineIdBits;        private static long timestampLeftShift = sequenceBits + machineIdBits + datacenterIdBits; //时间戳左移动位数就是机器码+计数器总字节数+数据字节数        public static long sequenceMask = -1L ^ -1L << (int)sequenceBits; //一微秒内可以产生计数,如果达到该值则等到下一微妙在进行生成        private static long lastTimestamp = -1L;//最后时间戳        private static object syncRoot = new object();//加锁对象        static Snowflake snowflake;        public static Snowflake Instance()        {            if (snowflake == null)                snowflake = new Snowflake();            return snowflake;        }        public Snowflake()        {            Snowflakes(0L, -1);        }        public Snowflake(long machineId)        {            Snowflakes(machineId, -1);        }        public Snowflake(long machineId, long datacenterId)        {            Snowflakes(machineId, datacenterId);        }        private void Snowflakes(long machineId, long datacenterId)        {            if (machineId >= 0)            {                if (machineId > maxMachineId)                {                    throw new Exception("机器码ID非法");                }                Snowflake.machineId = machineId;            }            if (datacenterId >= 0)            {                if (datacenterId > maxDatacenterId)                {                    throw new Exception("数据中心ID非法");                }                Snowflake.datacenterId = datacenterId;            }        }        ///         /// 生成当前时间戳        ///         /// 
毫秒
private static long GetTimestamp() { //让他2000年开始 return (long)(DateTime.UtcNow - new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds; } /// /// 获取下一微秒时间戳 /// /// ///
private static long GetNextTimestamp(long lastTimestamp) { long timestamp = GetTimestamp(); int count = 0; while (timestamp <= lastTimestamp)//这里获取新的时间,可能会有错,这算法与comb一样对机器时间的要求很严格 { count++; if (count > 10) throw new Exception("机器的时间可能不对"); Thread.Sleep(1); timestamp = GetTimestamp(); } return timestamp; } /// /// 获取长整形的ID /// ///
public long GetId() { lock (syncRoot) { long timestamp = GetTimestamp(); if (Snowflake.lastTimestamp == timestamp) { //同一微妙中生成ID sequence = (sequence + 1) & sequenceMask; //用&运算计算该微秒内产生的计数是否已经到达上限 if (sequence == 0) { //一微妙内产生的ID计数已达上限,等待下一微妙 timestamp = GetNextTimestamp(Snowflake.lastTimestamp); } } else { //不同微秒生成ID sequence = 0L; } if (timestamp < lastTimestamp) { throw new Exception("时间戳比上一次生成ID时时间戳还小,故异常"); } Snowflake.lastTimestamp = timestamp; //把当前时间戳保存为最后生成ID的时间戳 long Id = ((timestamp - twepoch) << (int)timestampLeftShift) | (datacenterId << (int)datacenterIdShift) | (machineId << (int)machineIdShift) | sequence; return Id; } } }
[TestClass]    public class SnowflakeUnitTest1    {        ///         /// 动态生产有规律的ID Snowflake算法是Twitter的工程师为实现递增而不重复的ID实现的        ///         [TestMethod]        public void SnowflakeTestMethod1()        {            var ids = new List
(); for (int i = 0; i < 1000000; i++)//测试同时100W有序ID { ids.Add(Snowflake.Instance().GetId()); } for (int i = 0; i < ids.Count - 1; i++) { Assert.IsTrue(ids[i] < ids[i+1]); } } }
namespace ConsoleApplicationTester{    class Program    {        static void Main(string[] args)        {            for (int i = 0; i < 1000; i++)            {                Console.WriteLine("开始执行 " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffffff") + "    " + Snowflake.Instance().GetId());                Console.WriteLine("Snowflake.maxMachineId:" + Snowflake.maxMachineId);            }        }    }}
你可能感兴趣的文章
Docker镜像与容器命令
查看>>
批量删除oracle中以相同类型字母开头的表
查看>>
Java基础学习总结(4)——对象转型
查看>>
BZOJ3239Discrete Logging——BSGS
查看>>
SpringMVC权限管理
查看>>
spring 整合 redis 配置
查看>>
cacti分组发飞信模块开发
查看>>
浅析LUA中游戏脚本语言之魔兽世界
查看>>
飞翔的秘密
查看>>
Red Hat 安装源包出错 Package xxx.rpm is not signed
查看>>
编译安装mysql-5.6.16.tar.gz
查看>>
活在当下
查看>>
每天进步一点----- MediaPlayer
查看>>
PowerDesigner中CDM和PDM如何定义外键关系
查看>>
跨域-学习笔记
查看>>
the assignment of reading paper
查看>>
android apk 逆向中常用工具一览
查看>>
MyEclipse 报错 Errors running builder 'JavaScript Validator' on project......
查看>>
Skip List——跳表,一个高效的索引技术
查看>>
Yii2单元测试初探
查看>>