一種基於Orleans的分布式Id生成方案


基於Orleans的分布式Id生成方案,因Orleans的單實例、單線程模型,讓這種實現變的簡單,貼出一種實現,歡迎大家提出意見

public interface ISequenceNoGenerator : Orleans.IGrainWithIntegerKey
{
   Task<Immutable<string>> GetNext();
}
public class SequenceNoGenerator : Orleans.Grain, ISequenceNoGenerator
 {
     private const int MaxSeed = 99999;
     private int _seed = 0;
     private int _currentSecondCounter = 0;
     Task<Immutable<string>> ISequenceNoGenerator.GetNext()
     {
         var oldCounter = this._currentSecondCounter;

         while (true)
         {
             this.UpdateCurrentTimestamp();

             if (oldCounter != this._currentSecondCounter)
                 this._seed = 1;
             else
             {
                 ++this._seed;
             }

             if (this._seed > MaxSeed) Task.Delay(100);
             else break;
         }

         var seq = DateTime.Now.ToString("yyyyMMdd") + this._currentSecondCounter.ToString() + this._seed.ToString();
         return Task.FromResult(seq.AsImmutable());
     }

     public override Task OnActivateAsync()
     {
         //延遲1秒啟動,防止Activation在某個機器上崩潰后,在集群中其它host上啟動時,sequenceNo在同一秒出現重復
          Task.Delay(1000);

         return base.OnActivateAsync();
     }

     private void UpdateCurrentTimestamp()
     {
         var currentTime = DateTime.Now;
         var currentDayStart = Convert.ToDateTime(currentTime.ToShortDateString());
         this._currentSecondCounter = (int)(new TimeSpan(currentTime.Ticks - currentDayStart.Ticks).TotalSeconds);
     }
 }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM