雪花算法 - Java示例

雪花算法java示例,每秒产生20万个以上ID。

package com.putdns.simple;

public class S {

 private static long lt = 0L;

 private static long sequence = 0L;

 private static final long initTime = 1568880207465L;

 private static final int mask = 2019;

 public static void main(String[] args) {
  S g = new S();
  int dbIndex = 12, machine = 12;
  for (int i = 0; i < 100; i++) {
   System.out.println(g.id(dbIndex, machine));
  }
 }

 public synchronized Long id(int db, int machine) {
  long ct = System.currentTimeMillis();
  if (ct < lt) {
   throw new RuntimeException();
  }
  if (ct == lt) {
   sequence = (sequence + 1) & mask;
   if (sequence == 0) {
    ct = System.currentTimeMillis();
    while (ct == lt) {
     ct = System.currentTimeMillis();
    }
   }
  } else {
   sequence = 0L;
  }
  Long id = ((ct - initTime) << 22) | (db << 17) | (machine << 12) | sequence;
  lt = ct;
  return id;
 }

}