gpt4 book ai didi

java - randomUUID 是否提供唯一 ID?

转载 作者:IT老高 更新时间:2023-10-28 21:04:20 26 4
gpt4 key购买 nike

我正在尝试为我的 REST API 创建 session token 。每次用户登录时,我都会通过

创建一个新 token
UUID token = UUID.randomUUID();
user.setSessionId(token.toString());
Sessions.INSTANCE.sessions.put(user.getName(), user.getSessionId());

但是,我不确定如何防止重复的 sessionTokens。

例如:是否存在用户1登录并获得 token 87955dc9-d2ca-4f79-b7c8-b0223a32532a和user2登录获得 token 的场景 token 87955dc9-d2ca-4f79-b7c8-b0223a32532a

有没有更好的方法来做到这一点?

最佳答案

如果你遇到 UUID 冲突,接下来去玩彩票。

来自维基百科:

Randomly generated UUIDs have 122 random bits. Out of a total of 128bits, four bits are used for the version ('Randomly generated UUID'),and two bits for the variant ('Leach-Salz').

With random UUIDs, thechance of two having the same value can be calculated usingprobability theory (Birthday paradox). Using the approximation

p(n)\approx 1-e^{-\tfrac{n^2}{{2x}}}

these are the probabilities of anaccidental clash after calculating n UUIDs, with x=2122:

n probability68,719,476,736 = 236 0.0000000000000004 (4 × 10−16)2,199,023,255,552 = 241 0.0000000000004 (4 × 10−13)70,368,744,177,664 = 246 0.0000000004 (4 × 10−10)

To put these numbers into perspective,the annual risk of someone being hit by a meteorite is estimated to beone chance in 17 billion, which means the probability is about0.00000000006 (6 × 10−11), equivalent to the odds of creating a few tens of trillions of > UUIDs in a year and having one duplicate. Inother words, only after generating 1 billion UUIDs every second forthe next 100 years, the probability of creating just one duplicatewould be about 50%. The probability of one duplicate would be about50% if every person on earth owns 600 million UUIDs.

关于java - randomUUID 是否提供唯一 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20999792/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com