如何设置MySQL分布式架构主键ID,为什么不能使用自增ID或者UUID做主键?

public class SnowflakeIdGenerator { // 起始的时间戳 private static final long START_STAMP = 1480166465631L; // 每一部分占用的位数 private static final long SEQUENCE_BIT = 12; private static final long MACHINE_BIT = 10; private static final long TIMESTAMP_BIT = 41; // 每一部分的最大值 private static final long MAX_SEQUENCE = -1L ^ (-1L << SEQUENCE_BIT); private static final long MAX_MACHINE_NUM = -1L ^ (-1L << MACHINE_BIT); // 每一部分向左的位移 private static final long MACHINE_LEFT = SEQUENCE_BIT; private static final long TIMESTAMP_LEFT = SEQUENCE_BIT + MACHINE_BIT; private long machineId; private long sequence = 0L; private long lastStamp = -1L; public SnowflakeIdGenerator(long machineId) { if (machineId > MAX_MACHINE_NUM || machineId < 0) { throw new IllegalArgumentException("machineId can't be greater than MAX_MACHINE_NUM or less than 0"); } this.machineId = machineId; } public synchronized long nextId() { long currStamp = getNewStamp(); if (currStamp < lastStamp) { throw new RuntimeException("Clock moved backwards. Refusing to generate id"); } if (currStamp == lastStamp) { sequence = (sequence + 1) & MAX_SEQUENCE; if (sequence == 0L) { currStamp = getNextStamp(lastStamp); } } else { sequence = 0L; } lastStamp = currStamp; return (currStamp - START_STAMP) << TIMESTAMP_LEFT | machineId << MACHINE_LEFT | sequence; } private long getNextStamp(long lastStamp) { long stamp = getNewStamp(); while (stamp <= lastStamp) { stamp = getNewStamp(); } return stamp; } private long getNewStamp() { return System.currentTimeMillis(); } }
上一篇:【计算机网络】--URL统一资源定位符


下一篇:基于Selenium+Python的web自动化测试框架