当前位置:网站首页>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());
边栏推荐
- 22-07-16 personal training match 3 competition experience
- 23.10 Admin features
- QSS add resource file of QT
- A summary of practical websites that won't brighten people's eyes
- JS tool function Encyclopedia
- 【搜索专题】看完必会的搜索问题之洪水覆盖
- 内存管理-动态分区分配方式模拟
- Leetcode and query question summary
- P1825 [USACO11OPEN]Corn Maze S
- When developing flutter, idea_ ID cannot solve the problem
猜你喜欢
![[untitled]](/img/3e/fb7c4d901643e6ea88a7d90ead045c.png)
[untitled]

Mysql8 one master one slave +mycat2 read write separation
![[untitled]](/img/89/c3ab79eb325f0136114a568745924b.png)
[untitled]

基于C#实现的文件管理文件系统

Cadence(十)走线技巧与注意事项

Excel delete blank lines

2022-7-8 personal qualifying 5 competition experience (supplementary)

有限元学习知识点备案

QT uses QSS to make a beautiful login interface (hand-in-hand teaching)

How to safely delete a useless activity in Android studio
随机推荐
Transfer guide printing system based on C language design
SSH,NFS,FTP
Spark SQL common date functions
General file upload vulnerability getshell of a digital campus system (penetration test -0day)
03异常处理,状态保持,请求钩子---04大型项目结构与蓝图
Why reserve a capacitor station on the clock output?
22-07-16 personal training match 3 competition experience
[recommended collection] summary of MySQL 30000 word essence - partitions, tables, databases and master-slave replication (V)
OA项目之我的会议(查询)
Leetcode and query question summary
Mysql8 one master one slave +mycat2 read write separation
2022-7-6 personal qualifying 3 competition experience
23.5 event listeners of application events and listeners
Arbitrum launched the anytrust chain to meet the diverse needs of ecological projects
Status management bloc provider geTx
Super nice navigation page (static page)
基于C#实现的文件管理文件系统
OA项目之我的会议(会议排座&送审)
Oracle 19C OCP 1z0-082 certification examination question bank 1
请问现在flinkcdc支持sqlserver实例名方式连接吗?