21xrx.com
2024-12-22 23:43:36 Sunday
登录
文章检索 我的文章 写文章
Java如何生成唯一ID?示例代码附详解
2023-06-17 17:22:05 深夜i     --     --
Java 唯一ID UUID Snowflake算法 原子量

在Java开发中,生成唯一的ID是非常常见的需求。以下是介绍生成唯一ID的几种方式,并提供示例代码。

1. UUID(通用唯一识别码)

UUID是128位的唯一标识符,通常由32个字符组成。它可以通过Java的UUID类来生成,代码示例如下:


String uuid = UUID.randomUUID().toString().replaceAll("-", "");

2. Snowflake算法

Snowflake算法是Twitter开源的分布式ID生成算法,它可以在分布式系统中生成唯一有序的ID。下面是示例代码:


public class SnowFlake {

  private final static long START_STMP = 1480166465631L;

  private final static long SEQUENCE_BIT = 12;

  private final static long MACHINE_BIT = 5;

  private final static long DATACENTER_BIT = 5;

  private final static long MAX_DATACENTER_NUM = -1L ^ (-1L << DATACENTER_BIT);

  private final static long MAX_MACHINE_NUM = -1L ^ (-1L << MACHINE_BIT);

  private final static long MAX_SEQUENCE = -1L ^ (-1L << SEQUENCE_BIT);

  private final static long MACHINE_LEFT = SEQUENCE_BIT;

  private final static long DATACENTER_LEFT = SEQUENCE_BIT + MACHINE_BIT;

  private final static long TIMESTMP_LEFT = DATACENTER_LEFT + DATACENTER_BIT;

  private long datacenterId;

  private long machineId;

  private long sequence = 0L;

  private long lastStmp = -1L;

  public SnowFlake(long datacenterId, long machineId) {

    if (datacenterId > MAX_DATACENTER_NUM || datacenterId < 0) {

      throw new IllegalArgumentException("datacenterId can't be greater than MAX_DATACENTER_NUM or less than 0");

    }

    if (machineId > MAX_MACHINE_NUM || machineId < 0) {

      throw new IllegalArgumentException("machineId can't be greater than MAX_MACHINE_NUM or less than 0");

    }

    this.datacenterId = datacenterId;

    this.machineId = machineId;

  }

  public synchronized long nextId() {

    long currStmp = getNewstmp();

    if (currStmp < lastStmp) {

      throw new RuntimeException("Clock moved backwards. Refusing to generate id");

    }

    if (currStmp == lastStmp) {

      sequence = (sequence + 1) & MAX_SEQUENCE;

      if (sequence == 0L) {

        currStmp = getNextMill();

      }

    } else

      sequence = 0L;

    

    lastStmp = currStmp;

    return (currStmp - START_STMP) << TIMESTMP_LEFT

        | datacenterId << DATACENTER_LEFT

        | machineId << MACHINE_LEFT

        | sequence;

  }

  private long getNextMill() {

    long mill = getNewstmp();

    while (mill <= lastStmp) {

      mill = getNewstmp();

    }

    return mill;

  }

  private long getNewstmp() {

    return System.currentTimeMillis();

  }

  public static void main(String[] args) {

    SnowFlake snowFlake = new SnowFlake(2, 3);

    for (int i = 0; i < 5; i++) {

      System.out.println(snowFlake.nextId());

    }

  }

}

3. 原子量+时间戳

原子量是线程安全的,可以通过AtomicLong类来实现。代码示例如下:


private static final AtomicLong atomicLong = new AtomicLong(1);

private static long lastTime = System.currentTimeMillis();

public synchronized static long getId() {

  long currentTime = System.currentTimeMillis();

  if (currentTime < lastTime) {

    throw new RuntimeException("Clock moved backwards.");

  }

  if (currentTime == lastTime) {

    atomicLong.getAndIncrement();

  } else {

    atomicLong.set(1);

    lastTime = currentTime;

  }

  return Long.valueOf(String.format("%d%03d", lastTime, atomicLong.getAndIncrement() % 1000));

}

综上所述,生成唯一ID的方式有很多,而每种方式都有着不同的适用场景。开发者们在使用时可以根据自身的业务需求选择最合适的方式。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复