有关全局ID,雪花(snowflake)算法的印证

上次简短的说一下: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

图片 1

全局ID的烈性探讨:https://q.cnblogs.com/q/53552/

其后在别国大牛的底子上重写修改了有的情节https://github.com/ccollie/snowflake-net,添加了部分诠释等【接济Core】。现在是足以去Nuget直接下载应用的:斯诺flake.Net

图片 2

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

测试用例:

图片 3

测试代码: 

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<long> set = 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⊙)…,举个例子:

测试代码不变的事态下,改这么一句:

图片 4

图片 5

 

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

图片 6

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

图片 7

 IdWorker.Init().NextId()