当前位置:网站首页>Typescript snowflake primary key generator
Typescript snowflake primary key generator
2022-07-26 08:47:00 【Code road hero】
newly build SnowflakeIdGenerate.ts
// src/utils/Snowflake.ts
/** * Snowflake Primary key generation algorithm * The complete algorithm is generated ID The length is 20 position * But because of js Maximum 9007199254740991, More will overflow , More special treatment is needed . * So set the length here as 16 position id. Turn down the data center to 1 position , Turn down the server to 1 position , Turn the sequence bit down to 10 position * This means that up to two data centers are supported , Each data center supports up to two servers */
export class SnowflakeIdGenerate {
private twepoch = 0;
private workerIdBits = 1;
private dataCenterIdBits = 1;
private maxWrokerId = -1 ^ (-1 << this.workerIdBits); // The value is :1
private maxDataCenterId = -1 ^ (-1 << this.dataCenterIdBits); // The value is :1
private sequenceBits = 10;
private workerIdShift = this.sequenceBits; // The value is :10
private dataCenterIdShift = this.sequenceBits + this.workerIdBits; // The value is :11
// private timestampLeftShift =
// this.sequenceBits + this.workerIdBits + this.dataCenterIdBits; // The value is :12
private sequenceMask = -1 ^ (-1 << this.sequenceBits); // The value is :4095
private lastTimestamp = -1;
private workerId = 1; // Set the default value , Take... From the environment variable
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 Maximum 9007199254740991, More will overflow
// exceed 32 Bit length , Doing bit operations will overflow , Become negative , So here we do multiplication directly , Multiplication expands storage
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();
};
}
Use
const idGenerate: SnowflakeIdGenerate = new SnowflakeIdGenerate();
console.log(idGenerate.generate());
边栏推荐
- KV database based on raft consensus protocol
- Replication of SQL injection vulnerability in the foreground of Pan micro e-cology8
- Spark SQL common date functions
- What are the differences in the performance of different usages such as count (*), count (primary key ID), count (field) and count (1)? That's more efficient
- Memory management - dynamic partition allocation simulation
- The effective condition of MySQL joint index and the invalid condition of index
- 2000年的教训。web3是否=第三次工业革命?
- P1825 [USACO11OPEN]Corn Maze S
- 海内外媒体宣发自媒体发稿要严格把握内容关
- 【FreeSwitch开发实践】自定义模块创建与使用
猜你喜欢

My meeting of OA project (meeting seating & submission for approval)

03异常处理,状态保持,请求钩子---04大型项目结构与蓝图

Mycat2 deploy master-slave MariaDB

Deploy prometheus+grafana monitoring platform

Spark scheduling analysis

【FreeSwitch开发实践】自定义模块创建与使用

2000年的教训。web3是否=第三次工业革命?

有限元学习知识点备案

Maximum common substring & regularity problem

基于Raft共识协议的KV数据库
随机推荐
Arbitrum Nova release! Create a low-cost and high-speed dedicated chain in the game social field
Registration of finite element learning knowledge points
[suggestions collection] summary of MySQL 30000 word essence - locking mechanism and performance tuning (IV) [suggestions collection]
为什么要在时钟输出上预留电容的工位?
基于C语言的哈夫曼转化软件
6、 Pinda general permission system__ pd-tools-log
Automation and disconnection monitoring of video addition
Oracle 19C OCP 1z0-083 question bank (1-6)
Spark persistence strategy_ Cache optimization
Kotlin program control
Mysql database connection / query index and other common syntax
基于C语言实现的人机交互软件
Flutter text is left aligned with no blank space in the middle
Study notes of automatic control principle --- stability analysis of control system
Mycat2 sub database and sub table
Kept dual machine hot standby
PXE principles and concepts
Please tell me if there is any way to increase the write out rate when the Flink SQL client is in the sink table. When synchronizing through sink table
Oracle 19C OCP certification examination software list
Oracle 19C OCP 1z0-082 certification examination question bank (36-41)