当前位置:网站首页>TypeScript版Snowflake主键生成器
TypeScript版Snowflake主键生成器
2022-07-26 08:39:00 【码道功臣】
新建 SnowflakeIdGenerate.ts
// src/utils/Snowflake.ts
/** * Snowflake主键生成算法 * 完整的算法是生成的ID长度为20位 * 但是由于js最大值9007199254740991,再多就会溢出,再多要特殊处理。 * 所以这里设置长度为16位id。将数据中心位调小到1位,将服务器位调小到1位,将序列位调小到10位 * 这意味着最多支持两个数据中心,每个数据中心最多支持两台服务器 */
export class SnowflakeIdGenerate {
private twepoch = 0;
private workerIdBits = 1;
private dataCenterIdBits = 1;
private maxWrokerId = -1 ^ (-1 << this.workerIdBits); // 值为:1
private maxDataCenterId = -1 ^ (-1 << this.dataCenterIdBits); // 值为:1
private sequenceBits = 10;
private workerIdShift = this.sequenceBits; // 值为:10
private dataCenterIdShift = this.sequenceBits + this.workerIdBits; // 值为:11
// private timestampLeftShift =
// this.sequenceBits + this.workerIdBits + this.dataCenterIdBits; // 值为:12
private sequenceMask = -1 ^ (-1 << this.sequenceBits); // 值为:4095
private lastTimestamp = -1;
private workerId = 1; //设置默认值,从环境变量取
private dataCenterId = 1;
private sequence = 0;
constructor(_workerId = 0, _dataCenterId = 0, _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;
}
private timeGen = (): number => {
return Date.now();
};
private tilNextMillis = (lastTimestamp): number => {
let timestamp = this.timeGen();
while (timestamp <= lastTimestamp) {
timestamp = this.timeGen();
}
return timestamp;
};
private nextId = (): number => {
let timestamp: number = 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;
// js 最大值 9007199254740991,再多就会溢出
// 超过 32 位长度,做位运算会溢出,变成负数,所以这里直接做乘法,乘法会扩大存储
const timestampPos = (timestamp - this.twepoch) * 4096;
const dataCenterPos = this.dataCenterId << this.dataCenterIdShift;
const workerPos = this.workerId << this.workerIdShift;
return timestampPos + dataCenterPos + workerPos + this.sequence;
};
generate = (): number => {
return this.nextId();
};
}
使用
const idGenerate: SnowflakeIdGenerate = new SnowflakeIdGenerate();
console.log(idGenerate.generate());
边栏推荐
- 23.5 event listeners of application events and listeners
- Run file command
- 基于C语言设计的换乘指南打印系统
- Add in the registry right click to open in vscode
- Automation and disconnection monitoring of video addition
- MySQL 8.0 OCP (1z0-908) has a Chinese exam
- Error handling response: Error: Syntax error, unrecognized expression: .c-container /deep/ .c-contai
- QT note 1
- Pxe原理和概念
- [recommended collection] summary of MySQL 30000 word essence - partitions, tables, databases and master-slave replication (V)
猜你喜欢

SSH,NFS,FTP

Winter vacation homework & Stamp cutting

Why reserve a capacitor station on the clock output?

Excel find duplicate lines

Excel delete blank lines

1、 Redis data structure

Super potential public chain dfinity -- the best time for DFI developers to enter

Mycat2 deploy master-slave MariaDB
![[time complexity, space complexity]](/img/f2/f82c7e0a6ab9f893023c2ddbac3431.png)
[time complexity, space complexity]
![[freeswitch development practice] use SIP client Yate to connect freeswitch for VoIP calls](/img/8b/d5792a00fc5798d3d960f1f1b1088e.png)
[freeswitch development practice] use SIP client Yate to connect freeswitch for VoIP calls
随机推荐
Oracle 19C OCP 1z0-083 question bank (1-6)
请问flink sql client 在sink表,有什么办法增大写出速率吗。通过sink表的同步时
Oracle 19C OCP 1z0-082 certification examination question bank (13-18)
Flutter custom player progress bar
P3743 kotori的设备
Spark scheduling analysis
Dear teachers, how can sqlserver get DDL in flinkcdc?
6、 Pinda general permission system__ pd-tools-log
Kotlin function
Foundry tutorial: writing scalable smart contracts in various ways (Part 1)
[suggestions collection] summary of MySQL 30000 word essence - locking mechanism and performance tuning (IV) [suggestions collection]
Mycat2 deploy master-slave MariaDB
Inaccurate problem of flutter fijkplayer seekto
基于C#实现的文件管理文件系统
Oracle 19C OCP 1z0-082 certification examination question bank (7-12)
Web3 Games: current situation and future
Registration of finite element learning knowledge points
Run file command
Nodejs2day (modularization of nodejs, NPM download package, module loading mechanism)
Kotlin variables and constants