这篇文章将为大家详细讲解有关如何进行关于全局ID、snowflake算法的分析,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。
一开始我用的是这个简化版本,后来发现有重复项。。。(demo:https://github.com/dunitian/TempCode/tree/master/2016-11-16/Twitter_Snowflake)

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

测试代码:
usingSystem;usingSystem.Collections.Generic;usingSystem.Threading;usingSystem.Threading.Tasks;usingSnowflake.Net;namespaceSnowflake.ZConsole{ classProgram { privatestaticintN = 2000000; privatestaticHashSet<long> set= newHashSet<long>(); privatestaticIdWorker worker = newIdWorker(1, 1); privatestaticinttaskCount = 0; staticvoidMain(string[] args) { Task.Run(() => GetID()); Task.Run(() => GetID()); Task.Run(() => GetID()); Task.Run(() => Printf()); Console.ReadKey(); } privatestaticvoidPrintf() { while(taskCount != 3) { Console.WriteLine("..."); Thread.Sleep(1000); } Console.WriteLine(set.Count == N * taskCount); } privatestaticobjecto = newobject(); privatestaticvoidGetID() { for(vari = 0; i < N; i++) { varid = 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⊙)…,举个例子:
测试代码不变的情况下,改这么一句:


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

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

关于如何进行关于全局ID、snowflake算法的分析就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
原创文章,作者:carmelaweatherly,如若转载,请注明出处:https://blog.ytso.com/tech/opensource/238710.html