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;
  • 相关阅读:
    mojo 接口示例
    MojoliciousLite: 实时的web框架 概述
    接口返回json
    centos 6.7 perl 版本 This is perl 5, version 22 安装DBI DBD
    centos 6.7 perl 5.22 安装DBD 需要使用老的perl版本
    商业智能改变汽车行业
    商业智能改变汽车行业
    读MBA经历回顾(上)目的决定手段——北漂18年(48)
    perl 升级到5.20版本
    Group Commit of Binary Log
  • 原文地址:https://www.cnblogs.com/wooroc/p/13792308.html
Copyright © 2011-2022 走看看