A .NET port of Twitter Snowflake ID generation algorithm.

文章推薦指數: 80 %
投票人數:10人

移植 Snowflake 的 ID 生成算法。

有关该算法的详情,请参阅. /// https://github.com/twitter/snowflake/tree/snowflake-2010。

/// . Skiptocontent Allgists BacktoGitHub Signin Signup Sign in Sign up {{message}} Instantlysharecode,notes,andsnippets. cheer-cheer/IdWorker.cs LastactiveAug2,2016 Star 0 Fork 0 Star Code Revisions 2 Embed Whatwouldyouliketodo? Embed Embedthisgistinyourwebsite. Share Copysharablelinkforthisgist. Clonevia HTTPS ClonewithGitorcheckoutwithSVNusingtherepository’swebaddress. LearnmoreaboutcloneURLs DownloadZIP A.NETportofTwitterSnowflakeIDgenerationalgorithm. Raw IdWorker.cs ThisfilecontainsbidirectionalUnicodetextthatmaybeinterpretedorcompileddifferentlythanwhatappearsbelow.Toreview,openthefileinaneditorthatrevealshiddenUnicodecharacters. LearnmoreaboutbidirectionalUnicodecharacters Showhiddencharacters usingSystem; usingMicrosoft.Extensions.DependencyInjection; usingMicrosoft.Extensions.DependencyInjection.Extensions; namespaceCheer.Gists.Utilities { publicinterfaceIIdWorker { longGetId(stringuserAgent=null); } ///

///移植Snowflake的ID生成算法。

有关该算法的详情,请参阅 ///https://github.com/twitter/snowflake/tree/snowflake-2010。

///
publicclassSnowflakeIdWorker :IIdWorker { privateconstintWorkerIdBits=5; privateconstintDataCenterIdBits=5; privateconstlongEpoch=1470103578152; publicconstlongMaxWorkerId=-1L^(-1L<MaxWorkerId||workerId<0) { thrownewArgumentOutOfRangeException(nameof(workerId),workerId, $"workeridcannotbegreaterthan{MaxWorkerId}orlessthan0."); } if(dataCenterId>MaxDataCenterId||dataCenterId<0) { thrownewArgumentOutOfRangeException(nameof(dataCenterId),dataCenterId, $"Datacenteridcannotbegreaterthan{MaxDataCenterId}orlessthan0."); } this.WorkerId=workerId; this.DataCenterId=dataCenterId; this.sequence=sequence; } publiclongWorkerId { get; privateset; } publiclongDataCenterId { get; privateset; } privatelongsequence; publicvirtuallongGetId(stringuserAgent=null) { returnNextId(); } privatelonglastTimestamp; protectedvirtuallongNextId() { lock(workerLock) { vartimestamp=TimeGen(); if(timestamp DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); } [Serializable] publicclassInvalidSystemClockException :Exception { publicInvalidSystemClockException(stringmessage=null,ExceptioninnerException=null) :base(message,innerException) { } protectedInvalidSystemClockException(SerializationInfoinfo,StreamingContextcontext) :base(info,context) { } } publicstaticclassIdWorkerExtensions { publicstaticIServiceCollectionUseSnowflake(thisIServiceCollectionservices, longworkerId,longdataCenterId,longsequence=0) { services.TryAddSingleton((p)=> { returnnewSnowflakeIdWorker(workerId,dataCenterId,sequence); }); returnservices; } } } Signupforfree tojointhisconversationonGitHub. Alreadyhaveanaccount? Signintocomment Youcan’tperformthatactionatthistime. Yousignedinwithanothertaborwindow.Reloadtorefreshyoursession. Yousignedoutinanothertaborwindow.Reloadtorefreshyoursession.



請為這篇文章評分?