微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

怎么使用javascript雪花算法生成随机ID

这篇文章主要介绍了怎么使用javascript雪花算法生成随机ID的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇怎么使用javascript雪花算法生成随机ID文章都会有所收获,下面我们一起来看看吧。

1、sNowflake-id插件 

import SNowflakeId from "sNowflake-id";

const guid = num => {
  const id= new SNowflakeId();
  return id.generate();
};

2、原生使用 

var SNowflake = /** @class */ (function() {
  function SNowflake(_workerId, _dataCenterId, _sequence) {
    this.twepoch = 1288834974657n;
    //this.twepoch = 0n;
    this.workerIdBits = 5n;
    this.dataCenterIdBits = 5n;
    this.maxWrokerId = -1n ^ (-1n << this.workerIdBits); // 值为:31
    this.maxDataCenterId = -1n ^ (-1n << this.dataCenterIdBits); // 值为:31
    this.sequenceBits = 12n;
    this.workerIdShift = this.sequenceBits; // 值为:12
    this.dataCenterIdShift = this.sequenceBits + this.workerIdBits; // 值为:17
    this.timestampLeftShift = this.sequenceBits + this.workerIdBits + this.dataCenterIdBits; // 值为:22
    this.sequenceMask = -1n ^ (-1n << this.sequenceBits); // 值为:4095
    this.lastTimestamp = -1n;
    //设置认值,从环境变量取
    this.workerId = 1n;
    this.dataCenterId = 1n;
    this.sequence = 0n;
    if(this.workerId > this.maxWrokerId || this.workerId < 0) {
      thrownew Error('_workerId must max than 0 and small than maxWrokerId-[' + this.maxWrokerId + ']');
    }
    if(this.dataCenterId > this.maxDataCenterId || this.dataCenterId < 0) {
      thrownew Error('_dataCenterId must max than 0 and small than maxDataCenterId-[' + this.maxDataCenterId + ']');
    }

    this.workerId = BigInt(_workerId);
    this.dataCenterId = BigInt(_dataCenterId);
    this.sequence = BigInt(_sequence);
  }
  SNowflake.prototype.tilNextMillis = function(lastTimestamp) {
    var timestamp = this.timeGen();
    while(timestamp <= lastTimestamp) {
      timestamp = this.timeGen();
    }
    return BigInt(timestamp);
  };
  SNowflake.prototype.timeGen = function() {
    return BigInt(Date.Now());
  };
  SNowflake.prototype.nextId = function() {
    var timestamp = this.timeGen();
    if(timestamp < this.lastTimestamp) {
      thrownew Error('Clock moved backwards. Refusing to generate id for ' +
        (this.lastTimestamp - timestamp));
    }
    if(this.lastTimestamp === timestamp) {
      this.sequence = (this.sequence + 1n) & this.sequenceMask;
      if(this.sequence === 0n) {
        timestamp = this.tilNextMillis(this.lastTimestamp);
      }
    } else {
      this.sequence = 0n;
    }
    this.lastTimestamp = timestamp;
    return((timestamp - this.twepoch) << this.timestampLeftShift) |
      (this.dataCenterId << this.dataCenterIdShift) |
      (this.workerId << this.workerIdShift) |
      this.sequence;
  };
  return SNowflake;
}());

console.log(new SNowflake(1n, 1n, 0n).nextId());
//1141531990672150528n

控制台输出1141531990672150528n为bigint格式, .toString()转为字符串格式即可

3、ES6使用

import bigInt from "big-integer";

const guid = () => {
  const SNowflake = /** @class */ (function() {
    function SNowflake(_workerId, _dataCenterId, _sequence) {
      // this.twepoch = 1288834974657;
      this.twepoch = 0;
      this.workerIdBits = 5;
      this.dataCenterIdBits = 5;
      this.maxWrokerId = -1 ^ (-1 << this.workerIdBits); // 值为:31
      this.maxDataCenterId = -1 ^ (-1 << this.dataCenterIdBits); // 值为:31
      this.sequenceBits = 12;
      this.workerIdShift = this.sequenceBits; // 值为:12
      this.dataCenterIdShift = this.sequenceBits + this.workerIdBits; // 值为:17
      this.timestampLeftShift = this.sequenceBits + this.workerIdBits + this.dataCenterIdBits; // 值为:22
      this.sequenceMask = -1 ^ (-1 << this.sequenceBits); // 值为:4095
      this.lastTimestamp = -1;
      //设置认值,从环境变量取
      this.workerId = 1;
      this.dataCenterId = 1;
      this.sequence = 0;
      if (this.workerId > this.maxWrokerId || this.workerId < 0) {
        throw new Error(
          'config.worker_id must max than 0 and small than maxWrokerId-[' + this.maxWrokerId + ']'
        );
      }
      if (this.dataCenterId > this.maxDataCenterId || this.dataCenterId < 0) {
        throw new Error(
          'config.data_center_id must max than 0 and small than maxDataCenterId-[' +
            this.maxDataCenterId +
            ']'
        );
      }
      this.workerId = _workerId;
      this.dataCenterId = _dataCenterId;
      this.sequence = _sequence;
    }
    SNowflake.prototype.tilNextMillis = function(lastTimestamp) {
      var timestamp = this.timeGen();
      while (timestamp <= lastTimestamp) {
        timestamp = this.timeGen();
      }
      return timestamp;
    };
    SNowflake.prototype.timeGen = function() {
      //new Date().getTime() === Date.Now()
      return Date.Now();
    };
    SNowflake.prototype.nextId = function() {
      var timestamp = this.timeGen();
      if (timestamp < this.lastTimestamp) {
        throw new Error(
          'Clock moved backwards. Refusing to generate id for ' + (this.lastTimestamp - timestamp)
        );
      }
      if (this.lastTimestamp === timestamp) {
        this.sequence = (this.sequence + 1) & this.sequenceMask;
        if (this.sequence === 0) {
          timestamp = this.tilNextMillis(this.lastTimestamp);
        }
      } else {
        this.sequence = 0;
      }
      this.lastTimestamp = timestamp;
      var shiftNum =
        (this.dataCenterId << this.dataCenterIdShift) |
        (this.workerId << this.workerIdShift) |
        this.sequence; // dataCenterId:1,workerId:1,sequence:0  shiftNum:135168
      var nfirst = new bigInt(String(timestamp - this.twepoch), 10);
      nfirst = nfirst.shiftLeft(this.timestampLeftShift);
      var nnextId = nfirst.or(new bigInt(String(shiftNum), 10)).toString(10);
      return nnextId;
    };
    return SNowflake;
  })();

  return new SNowflake(1, 1, 0).nextId();
};

guid()即可调用

4、多次重复调用出现一样id的bug

    console.log(guid(), new Date().getTime());
    console.log(guid(), new Date().getTime());
    console.log(guid(), new Date().getTime());
    console.log(guid(), new Date().getTime());
    console.log(guid(), new Date().getTime());
    console.log(guid(), new Date().getTime());
    console.log(guid(), new Date().getTime());
    console.log(guid(), new Date().getTime());
    console.log(guid(), new Date().getTime());
    console.log(guid(), new Date().getTime());
    console.log(guid(), new Date().getTime());
    console.log(guid(), new Date().getTime());

怎么使用javascript雪花算法生成随机ID

修改如下

import SNowflakeId from "sNowflake-id";

const guid = num => {
  const sNowflake = new SNowflakeId();
  let arr = [];
  for (let i = 0; i < num; i++) {
    arr.push(sNowflake.generate());
  }
  return num ? arr : sNowflake.generate();
};

单个调用 guid()

n个调用 guid(n)

JavaScript有什么特点

1、js属于一种解释性脚本语言;

2、在绝大多数浏览器的支持下,js可以在多种平台下运行,拥有着跨平台特性;

3、js属于一种弱类型脚本语言,对使用的数据类型未做出严格的要求,能够进行类型转换,简单又容易上手;

4、js语言安全性高,只能通过浏览器实现信息浏览或动态交互,从而有效地防止数据的丢失;

5、基于对象的脚本语言,js不仅可以创建对象,也能使用现有的对象。

关于“怎么使用javascript雪花算法生成随机ID”这篇文章内容就介绍到这里,感谢各位的阅读!相信大家对“怎么使用javascript雪花算法生成随机ID”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注编程之家行业资讯频道。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐