js实现snowFlake
时间: 2024-04-16 18:28:27 浏览: 30
Snowflake是一种分布式唯一ID生成算法,可以在分布式系统中生成全局唯一的ID。下面是一个用JavaScript实现Snowflake算法的示例代码:
```javascript
class Snowflake {
constructor(workerId, datacenterId) {
this.workerIdBits = 5;
this.datacenterIdBits = 5;
this.sequenceBits = 12;
this.maxWorkerId = -1 ^ (-1 << this.workerIdBits);
this.maxDatacenterId = -1 ^ (-1 << this.datacenterIdBits);
this.workerId = workerId;
this.datacenterId = datacenterId;
this.sequence = 0;
this.workerIdShift = this.sequenceBits;
this.datacenterIdShift = this.sequenceBits + this.workerIdBits;
this.timestampLeftShift = this.sequenceBits + this.workerIdBits + this.datacenterIdBits;
this.sequenceMask = -1 ^ (-1 << this.sequenceBits);
this.lastTimestamp = -1;
}
generateId() {
let timestamp = Date.now();
if (timestamp < this.lastTimestamp) {
throw new Error("Clock moved backwards. Refusing to generate id.");
}
if (timestamp === this.lastTimestamp) {
this.sequence = (this.sequence + 1) & this.sequenceMask;
if (this.sequence === 0) {
timestamp = this.waitNextMillis(this.lastTimestamp);
}
} else {
this.sequence = 0;
}
this.lastTimestamp = timestamp;
const id =
((timestamp - 1420070400000) << this.timestampLeftShift) |
(this.datacenterId << this.datacenterIdShift) |
(this.workerId << this.workerIdShift) |
this.sequence;
return id.toString();
}
waitNextMillis(lastTimestamp) {
let timestamp = Date.now();
while (timestamp <= lastTimestamp) {
timestamp = Date.now();
}
return timestamp;
}
}
// Usage example
const snowflake = new Snowflake(1, 1);
console.log(snowflake.generateId());
```
上述代码实现了一个Snowflake类,构造函数接受workerId和datacenterId作为参数。generateId方法用于生成唯一的ID,使用了当前时间戳、workerId和sequence等信息进行计算。在使用时,可以创建一个Snowflake实例,并调用generateId方法来生成唯一的ID。