问题描述
我需要生成一个随机字符串(8位字母数字代码)并将我的Tournament行保存到数据库中。
I need to generate a random string (8 digit alphanumeric code) and save it with my Tournament row into a database.
问题是此代码需要是在整个表格中是独一无二的(随机的)(因为我不希望它是可预测的(人们用它来加入锦标赛)。
Problem is that this code needs to be unique in the whole table and random (not incremental) because I don't want it to be predictable (people using it to join tournament).
所以我需要一些东西来创建一个代码但是当它已经在表中然后生成一个新代码。一种方法是生成代码,然后检查数据库存在,然后在发生冲突时生成新代码。但是这个解决方案有许多问题,比如它可以永远运行而且速度很慢。
So I need something to genreate a code but when it already is in table then generate new one. One way is to generate code, then check database existance, then generate new in case of conflict. But this solution have many problems like it can run forever and its is slow.
推荐答案
答案是使用,它结合了唯一部分和随机部分。
The answer is to use a unique identifier that combines a "unique" part and a "random" part.
- 唯一部分可以是单调增加的计数器,也可以是使用全周期生成的数字(在重复之前伪随机地循环通过其周期内的所有可能值)。
- 随机部分只是一个用加密随机数生成器生成的随机数(node.js有;检查文档)。一般来说,它越长,预测就越不可预测。
- The "unique" part can be a monotonically increasing counter, or it can be a number generated with a full-period linear congruential generator (which cycles pseudorandomly through all possible values in its period before repeating).
- The "random" part is simply a random number generated with a cryptographic random number generator (which node.js has; check the documentation). In general, the longer it is, the less predictable it will be.
此外,为了生成唯一标识符,还有没有什么理由将你自己限制在你现在正在做的8个字符的字母数字标识符。
Moreover, for the purposes of generating unique identifiers, there is little reason to limit yourself to 8-character alphanumeric identifiers as you're now doing.
这篇关于数据库表中唯一的随机字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!