使用时间戳作为主键时,避免主键约束违规

Raj*_*age 2 java mysql database primary-key

我有一个数据库表,其中主键被定义为时间戳.应用程序根据触发的特定事件将记录插入数据库,并且使用的时间戳将是创建此实例的时间戳.由于此应用程序在多个服务器上运行,并且该事件同时在多个服务器中同时触发,因此在某些情况下,由于主键冲突,数据不会插入到数据库中.

为了避免这种情况,我可以改变什么?我现在的想法是,

  1. 在执行数据库插入之前等待一段随机时间.

    Random r = new Random();
    long time = r.nextLong() % 1000;
    time = time < 0 ? -time : time; // making sure that the waiting time is positive
    try {
        Thread.sleep(time);
    } catch (InterruptedException e) {
        throw new CustomeException(e);
    }
    Table1DataAccess.getInstance().insert(new Date(), "some description"); // inserting data into the table which has two fields.
    
    Run Code Online (Sandbox Code Playgroud)
  2. 使主键成为复合键.

对我来说,它们都不是好的解决方案,有人能指出我正确的方向吗?

PS我尝试插入数据的表在Date类型中有timestamp列,我猜它只有几秒的精度.当我使用该类型时timestamp,它提供了默认的微秒精度,它最多可以提供纳秒.

Kus*_*han 5

不要将时间戳用作主键字段.

使用Integer或BigInt作为主键自动增量字段