【问题标题】:Unique ID Generation From DB value with 11 digits using Java causing Unique constraint exception使用 Java 从 11 位数字的 DB 值生成唯一 ID,导致唯一约束异常
【发布时间】:2022-01-04 07:20:51
【问题描述】:

我有一个要求,我们需要生成 11 个字符的唯一块 ID。

我们有以下逻辑来生成它,

public String generateBlockId(){
        boolean alreadyExists = true;
        String newBlockId = "";
        
        while(alreadyExists) {
        
            newBlockId = generateYYDDDSSSSSString();
            
            Allocation allocation = repo.findTopByBlockId(newBlockId);
            if(allocation == null) {
                blockIdAlreadyExists = false;
            }
        }
        
        return newBlockId;
    }
    
    
public String generateYYDDDSSSSSString() {
        String dateString;
        LocalDateTime now = LocalDateTime.now();
        Integer year = now.getYear() % 100;
        Integer day = now.getDayOfYear();
        Integer second = now.toLocalTime().toSecondOfDay();
        String YY = StringUtils.leftPad(year.toString(), 2, "0");
        String DDD = StringUtils.leftPad(day.toString(), 3, "0");
        String SSSSSS = StringUtils.leftPad(second.toString(), 6, "0");
        dateString = YY + DDD + SSSSSS;
        return dateString;
    }

我们一次最多有 100 个并发用户,当生成的 id 存储到数据库时,它会影响性能并导致唯一约束异常。

有没有更好的办法解决这个问题。

注意:业务要求只有11位数字。

【问题讨论】:

  • 嗯,时间戳很少是唯一的,因此有可能 2 个用户在同一秒内生成 id。为什么不在代码或数据库中使用简单的序列生成器来处理这个问题?
  • @Thomas。这只有11个字符,所以以后有可能会乱序!
  • 当然,但无论您如何生成这些数字,最终都会出现乱序。一个 11 位数字允许多达 1 万亿个唯一 ID,因此如果您担心您的应用程序会使用更多,那么使用秒精度的时间戳会更加冒险。

标签: java oracle unique-constraint unique-key


【解决方案1】:

首先要做的事情 - 也许你应该回到业务并验证他们为什么需要 11 位限制;)

无论如何,如果特定用户一次只能发出一个请求(即没有来自单个用户的并发请求),我会在生成的 ID 中包含用户 ID(或其中的一部分)。在这种情况下,生成的 id 不应重叠。

【讨论】:

    【解决方案2】:

    我想我可能没有得到这个问题,但我会尽力而为。

    也许更好的方法是使用 UUID?是否需要使用时间戳?

    我在下面添加了一个示例

        public static String generateId() {
        //Create new uuid
        UUID uuid = UUID.randomUUID();
        //Convert the uuid to string and strip it from "-"
        String id = uuid.toString().replace("-", "");
        //Trim the UUID and retrieve the chars until the 11th char.
        id = id.substring(0, 11);
        //Return the id back
        return id;
    }
    

    【讨论】:

      猜你喜欢
      • 2017-04-15
      • 2018-08-14
      • 2015-12-17
      • 2011-09-03
      • 2017-05-27
      • 1970-01-01
      • 2014-11-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多