0%
Theme NexT works best with JavaScript enabled
前言 Java雪花算法生成随机ID
源代码 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 public class SnowflakeIdGenerator { private final long startTime = 1498608000000L ; private final long workerIdBits = 5L ; private final long dataCenterIdBits = 5L ; private final long maxWorkerId = -1L ^ (-1L << workerIdBits); private final long maxDataCenterId = -1L ^ (-1L << dataCenterIdBits); private final long sequenceBits = 12L ; private final long workerIdMoveBits = sequenceBits; private final long dataCenterIdMoveBits = sequenceBits + workerIdBits; private final long timestampMoveBits = sequenceBits + workerIdBits + dataCenterIdBits; private final long sequenceMask = -1L ^ (-1L << sequenceBits); private long workerId; private long dataCenterId; private long sequence = 0L ; private long lastTimestamp = -1L ; public SnowflakeIdGenerator (long workerId, long dataCenterId) { if (workerId > maxWorkerId || workerId < 0 ) { throw new IllegalArgumentException (String.format("Worker Id can't be greater than %d or less than 0" , maxWorkerId)); } if (dataCenterId > maxDataCenterId || dataCenterId < 0 ) { throw new IllegalArgumentException (String.format("DataCenter Id can't be greater than %d or less than 0" , maxDataCenterId)); } this .workerId = workerId; this .dataCenterId = dataCenterId; } public synchronized long nextId () { long timestamp = currentTime(); if (timestamp < lastTimestamp) { throw new RuntimeException ( String.format("Clock moved backwards. Refusing to generate id for %d milliseconds" , lastTimestamp - timestamp)); } if (lastTimestamp == timestamp) { sequence = (sequence + 1 ) & sequenceMask; if (sequence == 0 ) { timestamp = blockTillNextMillis(lastTimestamp); } } else { sequence = 0L ; } lastTimestamp = timestamp; return ((timestamp - startTime) << timestampMoveBits) | (dataCenterId << dataCenterIdMoveBits) | (workerId << workerIdMoveBits) | sequence; } protected long blockTillNextMillis (long lastTimestamp) { long timestamp = currentTime(); while (timestamp <= lastTimestamp) { timestamp = currentTime(); } return timestamp; } protected long currentTime () { return System.currentTimeMillis(); } public static Long getId () { SnowflakeIdGenerator idWorker = new SnowflakeIdGenerator (0 , 0 ); return idWorker.nextId(); } }
完成 参考文献 Gitee——malitao