• Delphi雪花算法 生成随机数


    //  新建unit单元
    
    unit untSnowflake;
    
    interface
    
    uses
    SysUtils, SyncObjs, DateUtils;
    
    type
    TSnowflake = class
    private
    FOrgID: Integer; //机构号
    FMachineID: integer; //机器号
    FLocker: TCriticalSection;
    fTime: Int64; //时间戳
    fsn: int64; //序列
    public
    constructor Create;
    destructor Destroy; override;
    property MachineID: Integer read FMachineID write FMachineID;
    property OrgID: Integer read FOrgID write FOrgID;
    function Generate: Int64;
    end;
    
    implementation
    
    const
    Epoch: int64 = 1602262728000; //北京时间2018-10-15号 curtime := DateTimeToUnix(Now) * 1000;
    OrgBits: Byte = 5; //机构号 0..31
    MachineBits: Byte = 5; //机器号 0..31
    snBits: Byte = 12; //序列号12位
    timeShift: Byte = 22; //时间戳左移位数=序列号位数+机器号位数+机构号位数
    orgShift: Byte = 17; //机构号左移位数=序列号位数+机器号位数
    machineShift: Byte = 12; //工作站左移位数=序列号位数
    snMask: Word = 4095; //12位的计数序列号支持每个节点每毫秒产生4096个ID序号
    
    { TSnowflake }
    
    constructor TSnowflake.Create;
    begin
    FLocker := TCriticalSection.Create;
    end;
    
    destructor TSnowflake.Destroy;
    begin
    FLocker.Free;
    inherited;
    end;
    
    function TSnowflake.Generate: Int64;
    var
    curtime: Int64;
    begin
    FLocker.Acquire;
    try
    curtime := DateTimeToUnix(Now) * 1000;
    if curtime = fTime then
    begin
    fsn := (fsn + 1) and snMask;
    if fsn = 0 then
    begin
    while curtime <= fTime do
    curtime := DateTimeToUnix(Now) * 1000;
    end;
    end
    else
    fsn := 0;
    fTime := curtime;
    Result := (curtime - Epoch) shl timeShift
    or FOrgID shl orgShift
    or FMachineID shl machineShift
    or fsn;
    finally
    FLocker.Release;
    end;
    end;
    
    initialization
    
    
    end.
    
     
    
     
    
     
    
    // 方法调用
    
    var
    s: TSnowflake;
    i: Integer;
    begin
    s := TSnowflake.Create;
    s.OrgID := 8;
    s.MachineID := 10;
    for i := 1 to StrToInt(cxTextEdit1.Text) do
    begin
    cxMemo1.Lines.Add(IntToStr(s.Generate));
    Application.ProcessMessages;
    end;
    s.Free;
    end;
  • 相关阅读:
    toolblock 编写脚本并运用。
    C#等待子线程执行完毕
    win10+python3.7+dlib+opencv+face_recognition实现人脸识别
    c# tcp/ip通信
    【微信Xposed】kotlin反射异常RuntimeException:looper or serial is null
    安卓APK开启调试
    常用汇编指令对标志位的影响
    简单的.net反调试,调试检测
    虚拟机VMware和win10 hyper-v不兼容的问题
    对某城APP抓包分析--过SSL证书校验
  • 原文地址:https://www.cnblogs.com/wooroc/p/13792308.html
Copyright © 2020-2023  润新知