且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

关于全局ID,雪花(snowflake)算法的说明

更新时间:2022-08-12 23:00:49

上次简单的说一下:http://www.cnblogs.com/dunitian/p/6041745.html#uid

C#版本的国外朋友已经封装了,大家可以去看看:https://github.com/ccollie/snowflake-net

强大的网友出来个简化版本:http://blog.csdn.net/***/article/details/*** (地址我就不贴了,对前辈需要最起码的尊敬)

一开始我用的是这个简化版本,后来发现有重复项。。。(demo:https://github.com/dunitian/TempCode/tree/master/2016-11-16/Twitter_Snowflake

关于全局ID,雪花(snowflake)算法的说明

全局ID的激烈讨论:https://q.cnblogs.com/q/53552/

之后在外国大牛的基础上重写修改了部分内容https://github.com/ccollie/snowflake-net,添加了一些注解等【支持Core】。现在是可以去Nuget直接下载使用的:Snowflake.Net

关于全局ID,雪花(snowflake)算法的说明

源码地址:https://github.com/dunitian/snowflake-net

测试用例:

关于全局ID,雪花(snowflake)算法的说明

测试代码: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Snowflake.Net;
 
namespace Snowflake.ZConsole
{
    class Program
    {
        private static int N = 2000000;
        private static HashSet<longset new HashSet<long>();
        private static IdWorker worker = new IdWorker(1, 1);
        private static int taskCount = 0;
 
        static void Main(string[] args)
        {
            Task.Run(() => GetID());
            Task.Run(() => GetID());
            Task.Run(() => GetID());
 
            Task.Run(() => Printf());
            Console.ReadKey();
        }
 
        private static void Printf()
        {
            while (taskCount != 3)
            {
                Console.WriteLine("...");
                Thread.Sleep(1000);
            }
            Console.WriteLine(set.Count == N * taskCount);
        }
 
        private static object o = new object();
        private static void GetID()
        {
            for (var i = 0; i < N; i++)
            {
                var id = worker.NextId();
 
                lock (o)
                {
                    if (set.Contains(id))
                    {
                        Console.WriteLine("发现重复项 : {0}", id);
                    }
                    else
                    {
                        set.Add(id);
                    }
                }
 
            }
            Console.WriteLine($"任务{++taskCount}完成");
        }
    }
}

  

可能有些人只关心以后怎么用?==》

IdWorker worker = new IdWorker(1, 1); //大并发的情况下,减少new的次数可以有效避免重复的可能

var id = worker.NextId();

有可能上面的减少new有些同志不太懂,(⊙o⊙)…,举个例子:

测试代码不变的情况下,改这么一句:

关于全局ID,雪花(snowflake)算法的说明

关于全局ID,雪花(snowflake)算法的说明

 

完整调用demo:(https://github.com/dunitian/snowflake-net/tree/master/Demo

关于全局ID,雪花(snowflake)算法的说明

 core:(https://github.com/dunitian/snowflake-net/tree/master/Demo.Core)

关于全局ID,雪花(snowflake)算法的说明

 IdWorker.Init().NextId()


本文转自毒逆天博客园博客,原文链接:http://www.cnblogs.com/dunitian/p/6130543.html,如需转载请自行联系原作者