当前位置:网站首页>A method of generating non repeated numbers in nodejs

A method of generating non repeated numbers in nodejs

2022-06-24 10:43:00 easonxie

background

Recently when I was doing the demand , There is a management interface that needs to pass an unsigned when calling 32 Bit shaping file ID, That is to say 0 ~ 4294967295 Number between , Every time the interface is called, this file ID Can't repeat .

One 、 Database solutions

The more serious thing to do is , Create a database table for the file , Set a self increasing Int Type primary key id, Then every time you synchronize a file , Insert a file into the database table of the file , To generate a file id, Put this id Pass it to the backstage . But it's more troublesome , After all, our goal is to have a non - Duplicate File id, Doing too much for this purpose is not worth the loss .

Two 、 Using time stamps

JS The timestamp of is converted into a number 13 position ,32 The maximum unsigned integer number of bits is 4294967295, There is no way to treat the timestamp as a file directly id To use . You can change your mind . adopt JS Of Data.now() Get the current timestamp , Subtract a specified timestamp , Calculate the direct time interval between the two , Then multiply this time interval by 100, And then add 0-99 The random number .

The number thus generated , Bits and tens are random numbers , Hundreds or more are self incrementing timestamps . It is almost impossible to repeat , If greater accuracy is required , You can put 100 Switch to 1000, And then add 0-999 The random number .

/**
* precision  precision  100 1000 10000 
*/
function getNumberUid(precision){
  const rawPre = (Date.now() - new Date(1624206802955).getTime()) / precision;
  const preNumber = Number(rawPre.toFixed()) * precision;
  const randam = Math.floor(Math.random() * precision);
  return preNumber + randam;
}

3、 ... and 、 expand

The numbers generated in this way still have a very small probability of repetition , But it can basically handle the interface calls of the management side environment , Ensure no repetition . If it is the only one with a very large amount of data Id Generate , You still need to use a database or other methods . For example, you can refer to teacher liaoxuefeng's article 《 Distributed uniqueness ID generator 》

原网站

版权声明
本文为[easonxie]所创,转载请带上原文链接,感谢
https://yzsam.com/2021/06/20210621015130832v.html