JavaScript中的“雪花代码”通常指的是一种用于生成唯一标识符(ID)的算法,类似于Twitter的Snowflake算法。这种算法可以在分布式系统中生成全局唯一的ID,而不需要中央协调器。以下是关于雪花代码的基础概念、优势、类型、应用场景以及可能遇到的问题和解决方案。
雪花算法生成的ID是一个64位的整数,通常由以下部分组成:
以下是一个简单的JavaScript实现雪花算法的例子:
class Snowflake {
constructor(workerId, datacenterId, sequence = 0) {
this.twepoch = 1288834974657n;
this.workerIdBits = 5n;
this.datacenterIdBits = 5n;
this.maxWorkerId = -1n ^ (-1n << this.workerIdBits);
this.maxDatacenterId = -1n ^ (-1n << this.datacenterIdBits);
this.sequenceBits = 12n;
this.workerIdShift = this.sequenceBits;
this.datacenterIdShift = this.sequenceBits + this.workerIdBits;
this.timestampLeftShift = this.sequenceBits + this.workerIdBits + this.datacenterIdBits;
this.sequenceMask = -1n ^ (-1n << this.sequenceBits);
if (workerId > this.maxWorkerId || workerId < 0) {
throw new Error(`workerId can't be greater than ${this.maxWorkerId} or less than 0`);
}
if (datacenterId > this.maxDatacenterId || datacenterId < 0) {
throw new Error(`datacenterId can't be greater than ${this.maxDatacenterId} or less than 0`);
}
this.workerId = BigInt(workerId);
this.datacenterId = BigInt(datacenterId);
this.sequence = BigInt(sequence);
this.lastTimestamp = -1n;
}
tilNextMillis(lastTimestamp) {
let timestamp = this.timeGen();
while (timestamp <= lastTimestamp) {
timestamp = this.timeGen();
}
return BigInt(timestamp);
}
timeGen() {
return BigInt(Date.now());
}
nextId() {
let timestamp = this.timeGen();
if (timestamp < this.lastTimestamp) {
throw new Error(`Clock moved backwards. Refusing to generate id for ${this.lastTimestamp - timestamp} milliseconds`);
}
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;
}
}
// Usage
const snowflake = new Snowflake(1, 1);
console.log(snowflake.nextId());问题1:时钟回拨
问题2:ID重复
通过以上信息,你应该能够理解雪花代码的基本概念、优势、应用场景以及如何处理常见问题。
没有搜到相关的文章