繁体   English   中英

如何生成java中不能重复使用的随机ID号?

[英]How to generate random ID numbers that can't be reused in java?

对于我当前的 java 项目,我正在尝试为注册用户生成随机ID's 到目前为止,我一直使用min +(int) (Math.random()*((max-min)+1))作为我的公式来生成随机数。 我面临的问题是,有时数字会重复出现,而我的应用程序无法使用它们。

    int min = 1001;
    int max = 1050;
    
    for (int i=1; i<=1; i++)
    {
    int a = min +(int) (Math.random()*((max-min)+1));
    
    

     }
     
     
  

我尝试过使用和合并

    Integer[] arr = new Integer[100];
    for (int i = 1; i < arr.length; i++) {
    arr[i] = i;
    }
    Collections.shuffle(Arrays.asList(arr));

但是生成的数字会不断地以“空”的形式出现,它会重复循环几百次并淹没我的 txt 文件。

一般来说,随机生成器RandomMath.random()不是生成唯一 id 的正确方法。 正如您所提到的,它可以重复(而且肯定会)。

我会推荐两种生成ID的方法。

第一个是使用AtomicInteger 当您的ID应该是唯一的不是随机的时,这很好。

private static final AtomicInteger ID = new AtomicInteger(0);

public static String generateUniqueId() {
    return String.valueOf(ID.incrementAndGet());
}

第二个,对我来说更可取,是使用UUID 当您的ID应该像random一样唯一时,这很好。

public static String generateUniqueId() {
    return String.valueOf(UUID.randomUUID());
}

我可以提到的另一个是使用System.nanoTime()

public static String generateUniqueId() {
    return String.valueOf(System.nanoTime());
}

很久以前,我进行了一些调查,发现这对于正常的有效载荷来说非常稳定。 但总的来说,如果您构建这样一个应该经常生成ID的系统,它可以检索相同的值。

我建议不要生成数字,而是生成 UUID。 发生碰撞的机会要小得多。

UUID id = UUID.randomUUID();

否则,如果您想坚持使用数字,我建议您在应用程序中实现自己的一些序列服务。

import java.util.concurrent.atomic.AtomicLong;

public class SequenceService {

    private final AtomicLong ids;

    public SequenceService() {

        long initialValue = getInitialValue();
        this.ids = new AtomicLong(initialValue);
    }

    public long generateNextId() {
        return ids.incrementAndGet();
    }

    private long getInitialValue() {
        // this methods reads the last known leased id (e.g. from the file system)
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM