import java.util.ArrayList; import java.util.List; import java.util.Random; public final class GeneratedKeys { private static final Random RANDOM = new Random(); private static final int MAX_SIZE = 1050; //最多不超過1050條 private static final List<Long> LOCAL_TIMESTAMP_KEY_POOL = new ArrayList<>(MAX_SIZE); /** * 利用本地生成時間戳,爲主鍵 * * @return */ static synchronized public long localTimestampKey() { //若是本地主鍵池中大於MAX_SIZE個,那麼就將其清除,防止內存溢出 if (LOCAL_TIMESTAMP_KEY_POOL.size() > MAX_SIZE) { LOCAL_TIMESTAMP_KEY_POOL.subList(LOCAL_TIMESTAMP_KEY_POOL.size() - 120, LOCAL_TIMESTAMP_KEY_POOL.size()).clear(); } long timeStamp = System.currentTimeMillis() * 1000 + getSlot(); while (LOCAL_TIMESTAMP_KEY_POOL.contains(timeStamp)) { int i = 110000; //在此等侍 while (i > 0) { i--; } timeStamp = System.currentTimeMillis() * 1000 + getSlot(); } LOCAL_TIMESTAMP_KEY_POOL.add(0, timeStamp); return timeStamp; } /** * 獲取111-999 之間的數 * * @author Canaan * @date 2019/6/9 18:33 */ private static int getSlot() { StringBuilder slot = new StringBuilder(); for (int i = 0; i < 3; i++) { slot.append(RANDOM.nextInt(10)); } return Integer.valueOf(slot.toString()); } }
這個不能集羣使用java