来自mybatis-plus

    1. /*
    2. * Copyright (c) 2011-2020, baomidou (jobob@qq.com).
    3. * <p>
    4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
    5. * use this file except in compliance with the License. You may obtain a copy of
    6. * the License at
    7. * <p>
    8. * https://www.apache.org/licenses/LICENSE-2.0
    9. * <p>
    10. * Unless required by applicable law or agreed to in writing, software
    11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
    12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
    13. * License for the specific language governing permissions and limitations under
    14. * the License.
    15. */
    16. import java.lang.management.ManagementFactory;
    17. import java.net.InetAddress;
    18. import java.net.NetworkInterface;
    19. import java.util.concurrent.ThreadLocalRandom;
    20. import org.apache.ibatis.logging.Log;
    21. import org.apache.ibatis.logging.LogFactory;
    22. /**
    23. * 分布式高效有序ID生产黑科技(sequence)
    24. * <p>优化开源项目:https://gitee.com/yu120/sequence</p>
    25. *
    26. * @author hubin
    27. * @since 2016-08-18
    28. */
    29. public class Sequence {
    30. private static final Log logger = LogFactory.getLog(Sequence.class);
    31. /**
    32. * 时间起始标记点,作为基准,一般取系统的最近时间(一旦确定不能变动)
    33. */
    34. private final long twepoch = 1288834974657L;
    35. /**
    36. * 机器标识位数
    37. */
    38. private final long workerIdBits = 5L;
    39. private final long datacenterIdBits = 5L;
    40. private final long maxWorkerId = -1L ^ (-1L << workerIdBits);
    41. private final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
    42. /**
    43. * 毫秒内自增位
    44. */
    45. private final long sequenceBits = 12L;
    46. private final long workerIdShift = sequenceBits;
    47. private final long datacenterIdShift = sequenceBits + workerIdBits;
    48. /**
    49. * 时间戳左移动位
    50. */
    51. private final long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
    52. private final long sequenceMask = -1L ^ (-1L << sequenceBits);
    53. private final long workerId;
    54. /**
    55. * 数据标识 ID 部分
    56. */
    57. private final long datacenterId;
    58. /**
    59. * 并发控制
    60. */
    61. private long sequence = 0L;
    62. /**
    63. * 上次生产 ID 时间戳
    64. */
    65. private long lastTimestamp = -1L;
    66. public Sequence() {
    67. this.datacenterId = getDatacenterId(maxDatacenterId);
    68. this.workerId = getMaxWorkerId(datacenterId, maxWorkerId);
    69. }
    70. /**
    71. * 有参构造器
    72. *
    73. * @param workerId 工作机器 ID
    74. * @param datacenterId 序列号
    75. */
    76. public Sequence(long workerId, long datacenterId) {
    77. Assert.isFalse(workerId > maxWorkerId || workerId < 0,
    78. String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
    79. Assert.isFalse(datacenterId > maxDatacenterId || datacenterId < 0,
    80. String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId));
    81. this.workerId = workerId;
    82. this.datacenterId = datacenterId;
    83. }
    84. /**
    85. * 获取 maxWorkerId
    86. */
    87. protected static long getMaxWorkerId(long datacenterId, long maxWorkerId) {
    88. StringBuilder mpid = new StringBuilder();
    89. mpid.append(datacenterId);
    90. String name = ManagementFactory.getRuntimeMXBean().getName();
    91. if (StringUtils.isNotBlank(name)) {
    92. /*
    93. * GET jvmPid
    94. */
    95. mpid.append(name.split(StringPool.AT)[0]);
    96. }
    97. /*
    98. * MAC + PID 的 hashcode 获取16个低位
    99. */
    100. return (mpid.toString().hashCode() & 0xffff) % (maxWorkerId + 1);
    101. }
    102. /**
    103. * 数据标识id部分
    104. */
    105. protected static long getDatacenterId(long maxDatacenterId) {
    106. long id = 0L;
    107. try {
    108. InetAddress ip = InetAddress.getLocalHost();
    109. NetworkInterface network = NetworkInterface.getByInetAddress(ip);
    110. if (network == null) {
    111. id = 1L;
    112. } else {
    113. byte[] mac = network.getHardwareAddress();
    114. if (null != mac) {
    115. id = ((0x000000FF & (long) mac[mac.length - 1]) | (0x0000FF00 & (((long) mac[mac.length - 2]) << 8))) >> 6;
    116. id = id % (maxDatacenterId + 1);
    117. }
    118. }
    119. } catch (Exception e) {
    120. logger.warn(" getDatacenterId: " + e.getMessage());
    121. }
    122. return id;
    123. }
    124. /**
    125. * 获取下一个 ID
    126. *
    127. * @return 下一个 ID
    128. */
    129. public synchronized long nextId() {
    130. long timestamp = timeGen();
    131. //闰秒
    132. if (timestamp < lastTimestamp) {
    133. long offset = lastTimestamp - timestamp;
    134. if (offset <= 5) {
    135. try {
    136. wait(offset << 1);
    137. timestamp = timeGen();
    138. if (timestamp < lastTimestamp) {
    139. throw new RuntimeException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", offset));
    140. }
    141. } catch (Exception e) {
    142. throw new RuntimeException(e);
    143. }
    144. } else {
    145. throw new RuntimeException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", offset));
    146. }
    147. }
    148. if (lastTimestamp == timestamp) {
    149. // 相同毫秒内,序列号自增
    150. sequence = (sequence + 1) & sequenceMask;
    151. if (sequence == 0) {
    152. // 同一毫秒的序列数已经达到最大
    153. timestamp = tilNextMillis(lastTimestamp);
    154. }
    155. } else {
    156. // 不同毫秒内,序列号置为 1 - 3 随机数
    157. sequence = ThreadLocalRandom.current().nextLong(1, 3);
    158. }
    159. lastTimestamp = timestamp;
    160. // 时间戳部分 | 数据中心部分 | 机器标识部分 | 序列号部分
    161. return ((timestamp - twepoch) << timestampLeftShift)
    162. | (datacenterId << datacenterIdShift)
    163. | (workerId << workerIdShift)
    164. | sequence;
    165. }
    166. protected long tilNextMillis(long lastTimestamp) {
    167. long timestamp = timeGen();
    168. while (timestamp <= lastTimestamp) {
    169. timestamp = timeGen();
    170. }
    171. return timestamp;
    172. }
    173. protected long timeGen() {
    174. return SystemClock.now();
    175. }
    176. }
    /*
     * Copyright (c) 2011-2020, baomidou (jobob@qq.com).
     * <p>
     * Licensed under the Apache License, Version 2.0 (the "License"); you may not
     * use this file except in compliance with the License. You may obtain a copy of
     * the License at
     * <p>
     * https://www.apache.org/licenses/LICENSE-2.0
     * <p>
     * Unless required by applicable law or agreed to in writing, software
     * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
     * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
     * License for the specific language governing permissions and limitations under
     * the License.
     */
    
    import java.sql.Timestamp;
    import java.util.concurrent.Executors;
    import java.util.concurrent.ScheduledExecutorService;
    import java.util.concurrent.TimeUnit;
    import java.util.concurrent.atomic.AtomicLong;
    
    /**
     * 高并发场景下System.currentTimeMillis()的性能问题的优化
     *
     * <p>System.currentTimeMillis()的调用比new一个普通对象要耗时的多(具体耗时高出多少我还没测试过,有人说是100倍左右)</p>
     * <p>System.currentTimeMillis()之所以慢是因为去跟系统打了一次交道</p>
     * <p>后台定时更新时钟,JVM退出时,线程自动回收</p>
     * <p>10亿:43410,206,210.72815533980582%</p>
     * <p>1亿:4699,29,162.0344827586207%</p>
     * <p>1000万:480,12,40.0%</p>
     * <p>100万:50,10,5.0%</p>
     *
     * @author hubin
     * @since 2016-08-01
     */
    public class SystemClock {
    
        private final long period;
        private final AtomicLong now;
    
        private SystemClock(long period) {
            this.period = period;
            this.now = new AtomicLong(System.currentTimeMillis());
            scheduleClockUpdating();
        }
    
        private static SystemClock instance() {
            return InstanceHolder.INSTANCE;
        }
    
        public static long now() {
            return instance().currentTimeMillis();
        }
    
        public static String nowDate() {
            return new Timestamp(instance().currentTimeMillis()).toString();
        }
    
        private void scheduleClockUpdating() {
            ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(runnable -> {
                Thread thread = new Thread(runnable, "System Clock");
                thread.setDaemon(true);
                return thread;
            });
            scheduler.scheduleAtFixedRate(() -> now.set(System.currentTimeMillis()), period, period, TimeUnit.MILLISECONDS);
        }
    
        private long currentTimeMillis() {
            return now.get();
        }
    
        private static class InstanceHolder {
            public static final SystemClock INSTANCE = new SystemClock(1);
        }
    }