Java 使用 apache commons 的 RandomStringUtils 生成唯一键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20064385/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 22:47:32  来源:igfitidea点击:

Generating unique keys using RandomStringUtils of apache commons

javajakarta-eeapache-commonshashcode

提问by нα???z

Please find the below code which I've used to generate random strings using RandomStringUtilsof apache commons.

请找到我用来使用apache commons 的RandomStringUtils生成随机字符串的以下代码。

String key = RandomStringUtils.random(5, String.valueOf(System.currentTimeMillis()));

I am limiting the key to 5 characters. My purpose is generating unique keys for each records when I'm inserting a new record to DB. Will the above code be suitable for corresponding task and could I be assured that I will get a unique key from the above code each time inserting a new record.

我将密钥限制为 5 个字符。我的目的是在向数据库插入新记录时为每条记录生成唯一键。上面的代码是否适用于相应的任务,我可以放心,每次插入新记录时,我都会从上面的代码中获得一个唯一的键。

采纳答案by Geo

A random sequence of strings will always have a possibility of repeating, otherwise it's not really random. RandomStringUtilsis not really random, but it's trying to be as close to random as it can be, which seems contrary to your goal. If you must use randomly generated keys, then you should at least use java.util.UUID.randomUUIDbecause that is made to be used that way.

一个随机的字符串序列总是有重复的可能性,否则它就不是真正随机的。RandomStringUtils并不是真正随机,但它试图尽可能接近随机,这似乎与您的目标相反。如果您必须使用随机生成的密钥,那么您至少应该使用java.util.UUID.randomUUID,因为它是用来这样使用的。

You may find this link interesting: Generating unique IDs

您可能会发现此链接很有趣:生成唯一 ID

回答by Dumindu Pallewela

No, random doesn't mean unique. You can try using UUIDs to generate unique keys.

不,随机并不意味着唯一。您可以尝试使用 UUID 生成唯一键。

回答by avec

You can do it with RandomStringUtils, but you also have to test the id before trying to insert it.

您可以使用 RandomStringUtils 来完成,但您还必须在尝试插入之前测试 id。

  1. Generate
  2. Does it already exist?
  1. 产生
  2. 它已经存在了吗?

if yes goto 1 if no insert id

如果是,则转到 1 如果没有插入 ID

An UUID is very long and might not be what you want.

UUID 很长,可能不是您想要的。