zoukankan      html  css  js  c++  java
  • 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;
  • 相关阅读:
    Linux 配置 SSL 证书
    freemarker 异常处理
    StringTemplateLoader的用法
    序列的重点知识小结
    Linux下安装lrzsz上传下载工具
    ajax技术
    Response对象介绍(服务器到客户端)
    Request对象介绍(客户端到服务器)
    JSP--内置对象&动作标签介绍
    JSP--常用指令
  • 原文地址:https://www.cnblogs.com/wooroc/p/13792308.html
Copyright © 2011-2022 走看看