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 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
| package com.bjtcrj.scm.common.utils;
public class SnowFlakeID { private long sequence; private long sequenceBits = 12L; private long maxSequence = -1 ^ (-1 << sequenceBits);
private long workerId; private long workerIdBits = 5L; private long maxWorkerId = -1 ^ (-1 << workerIdBits); private long workerIdMoveBits = sequenceBits; private long workerIdAfterMove = 0L;
private long workerCenterId; private long workerCenterIdBits = 5L; private long maxWorkerCenterId = -1 ^ (-1 << workerCenterIdBits); private long workerCenterIdMoveBits = workerIdBits + workerIdMoveBits; private long workerCenterIdAfterMove = 0L;
private long lastTimestamp = -1L; private long initTimestamp = 1588518046057L; private long timestampMoveBits = workerCenterIdBits + workerCenterIdMoveBits;
public SnowFlakeID(long workerCenterId, long workerId) { if (workerCenterId < 0 || workerCenterId > maxWorkerCenterId) { throw new IllegalArgumentException("workerCenterId is illegal"); } if (workerId < 0 || workerId > maxWorkerId) { throw new IllegalArgumentException("workerId is illegal"); } this.workerCenterId = workerCenterId; this.workerId = workerId; this.workerCenterIdAfterMove = this.workerCenterId << this.workerCenterIdMoveBits; this.workerIdAfterMove = this.workerCenterId << this.workerCenterIdMoveBits; }
public synchronized long nextId() { long currentTimestamp = timestamp(); if (currentTimestamp < lastTimestamp) { String s = String.format("currentTimestamp is earlier than lastTimestamp,lastTimestamp=%s,currentTimestamp=%s", lastTimestamp, currentTimestamp); System.out.println(s); currentTimestamp = lastTimestamp; } if (currentTimestamp == lastTimestamp) { sequence = (sequence + 1) & maxSequence; if (sequence == 0L) { currentTimestamp = nextTimestamp(currentTimestamp); } } else { sequence = 0L; } lastTimestamp = currentTimestamp; return ((currentTimestamp - initTimestamp) << timestampMoveBits) | workerCenterIdAfterMove | workerIdAfterMove | sequence; }
public long nextTimestamp(long timestamp) { long timestamp1 = 0L; do { timestamp1 = timestamp(); } while (timestamp >= timestamp1); return timestamp1; }
public long timestamp() { return System.currentTimeMillis(); }
public static void main(String[] args) throws InterruptedException {
long startTime = System.currentTimeMillis(); for (int i = 0; i < 30; i++) { System.out.println(getId()); } System.out.println("耗时:" + (System.currentTimeMillis() - startTime) / 1000.0d + "秒"); }
private static SnowFlakeID snowFlakeID = new SnowFlakeID(1, 1); public static long getId() { return snowFlakeID.nextId(); } }
|