TS 生成雪花ID
时间: 2023-07-04 20:13:16 浏览: 47
好的,以下是 TypeScript 实现的雪花 ID 生成器:
```typescript
class SnowflakeGenerator {
private workerIdBits = 5;
private datacenterIdBits = 5;
private sequenceBits = 12;
private maxWorkerId = -1 ^ (-1 << this.workerIdBits);
private maxDatacenterId = -1 ^ (-1 << this.datacenterIdBits);
private sequenceMask = -1 ^ (-1 << this.sequenceBits);
private workerIdShift = this.sequenceBits;
private datacenterIdShift = this.sequenceBits + this.workerIdBits;
private timestampLeftShift = this.sequenceBits + this.workerIdBits + this.datacenterIdBits;
private lastTimestamp = -1;
private sequence = 0;
private workerId: number;
private datacenterId: number;
constructor(workerId: number, datacenterId: number) {
if (workerId > this.maxWorkerId || workerId < 0) {
throw new Error(`Worker ID must be between 0 and ${this.maxWorkerId}`);
}
if (datacenterId > this.maxDatacenterId || datacenterId < 0) {
throw new Error(`Datacenter ID must be between 0 and ${this.maxDatacenterId}`);
}
this.workerId = workerId;
this.datacenterId = datacenterId;
}
private timeGen(): number {
return Date.now();
}
private tilNextMillis(lastTimestamp: number): number {
let timestamp = this.timeGen();
while (timestamp <= lastTimestamp) {
timestamp = this.timeGen();
}
return timestamp;
}
public nextId(): bigint {
let timestamp = this.timeGen();
if (timestamp < this.lastTimestamp) {
throw new Error(`Clock moved backwards. Refusing to generate id for ${this.lastTimestamp - timestamp} milliseconds`);
}
if (timestamp === this.lastTimestamp) {
this.sequence = (this.sequence + 1) & this.sequenceMask;
if (this.sequence === 0) {
timestamp = this.tilNextMillis(this.lastTimestamp);
}
} else {
this.sequence = 0;
}
this.lastTimestamp = timestamp;
return (
BigInt(timestamp) << BigInt(this.timestampLeftShift) |
BigInt(this.datacenterId) << BigInt(this.datacenterIdShift) |
BigInt(this.workerId) << BigInt(this.workerIdShift) |
BigInt(this.sequence)
);
}
}
```
使用示例:
```typescript
const generator = new SnowflakeGenerator(1, 1);
console.log(generator.nextId()); // 输出类似 1076853241037248n 的大整数
```
这个实现是基于 Twitter 的雪花算法,使用了 TypeScript 语言。在构造函数中传入 workerId 和 datacenterId 两个参数,用于生成唯一的 ID。调用 `nextId()` 方法可以获得一个新的 ID。