天天看点

MyBatis Plus 源码 | 主键ASSIGN_ID生成方式的雪花改进版算法分析MyBatis Plus中主键生成方式ASSIGN_ID的算法分析

文章目录

  • MyBatis Plus中主键生成方式ASSIGN_ID的算法分析
    • 前言
    • 1. MybatisDefaultParameterHandler
    • 2. DefaultIdentifierGenerator
    • 3. Sequence

MyBatis Plus中主键生成方式ASSIGN_ID的算法分析

前言

MyBatis Plus 中提供了 ASSIGN_ID 这种方式生成主键,使用起来非常方便,只要在PO上定义一下就可以了,例如:

public class Order extends Model<Order> {

    @TableId(value = "id", type = IdType.ASSIGN_ID)
    private Long id;

    //...
}
           

这样在保存的时候,MyBatis Plus会负责生成主键值,自动设置到字段id中。 一直好奇这个主键是怎么生成的,抽时间查看了一下源码,特意记录一下。

1. MybatisDefaultParameterHandler

通过看MyBatis Plus的文档,发现这个主键生成过程应该是在ParameterHandler中进行处理的。在MyBatis Plus中ParameterHandler是用来设置参数规则的,当StatementHandler调用prepare方法之后,接下来就是调用它来进行设置参数。

对ASSIGN_ID进行处理的的地方是在MybatisDefaultParameterHandler中(在3.4.x版本中,该类改为MybatisParameterHandler),该类在包com.baomidou.mybatisplus.core中。对主键处理的代码在populateKeys这个方法中:

/**
 * 填充主键
 *
 * @param tableInfo  数据库表反射信息
 * @param metaObject 元数据对象
 * @param entity     实体信息
 */
protected static void populateKeys(TableInfo tableInfo, MetaObject metaObject, Object entity) {
    final IdType idType = tableInfo.getIdType();
    final String keyProperty = tableInfo.getKeyProperty();
    if (StringUtils.isNotBlank(keyProperty) && null != idType && idType.getKey() >= 3) {
        final IdentifierGenerator identifierGenerator = GlobalConfigUtils.getGlobalConfig(tableInfo.getConfiguration()).getIdentifierGenerator();
        Object idValue = metaObject.getValue(keyProperty);
        // 此处判断是否idValue是否存在,不存在的话就要根据类型进行计算赋值
        if (StringUtils.checkValNull(idValue)) {
            if (idType.getKey() == IdType.ASSIGN_ID.getKey()) { // 此处处理ASSIGN_ID类型的主键生成算法
                if (Number.class.isAssignableFrom(tableInfo.getKeyType())) {
                    // 此处调用IdentitifierGenerator生成主键
                    metaObject.setValue(keyProperty, identifierGenerator.nextId(entity));
                } else {
                    metaObject.setValue(keyProperty, identifierGenerator.nextId(entity).toString());
                }
            } else if (idType.getKey() == IdType.ASSIGN_UUID.getKey()) { // 此处处理ASSIGN_UUID类型的主键生成算法
                metaObject.setValue(keyProperty, identifierGenerator.nextUUID(entity));
            }
        }
    }
}
           

2. DefaultIdentifierGenerator

此类在包com.baomidou.mybatisplus.core.incrementer中。代码如下:

public class DefaultIdentifierGenerator implements IdentifierGenerator {

    private final Sequence sequence;

    public DefaultIdentifierGenerator() {
        this.sequence = new Sequence();
    }

    public DefaultIdentifierGenerator(long workerId, long dataCenterId) {
        this.sequence = new Sequence(workerId, dataCenterId);
    }

    public DefaultIdentifierGenerator(Sequence sequence) {
        this.sequence = sequence;
    }

    @Override
    public Long nextId(Object entity) {
        // 此处调用Sequence的nextId算法生成真正的主键值
        return sequence.nextId();
    }
}
           

3. Sequence

此类在包com.baomidou.mybatisplus.core.toolkit中。注意:以下代码进行了缩减。

public class Sequence {
    /**
     * 时间起始标记点,作为基准,一般取系统的最近时间(一旦确定不能变动)
     */
    private final long twepoch = 1288834974657L;
    /**
     * 机器标识位数
     */
    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 workerIdShift = sequenceBits;
    private final long datacenterIdShift = sequenceBits + workerIdBits;
    /**
     * 时间戳左移动位
     */
    private final long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
    private final long sequenceMask = -1L ^ (-1L << sequenceBits);


    public Sequence() {
        this.datacenterId = getDatacenterId(maxDatacenterId);
        this.workerId = getMaxWorkerId(datacenterId, maxWorkerId);
    }


    /**
     * 数据标识id部分
     */
    protected static long getDatacenterId(long maxDatacenterId) {
        long id = 0L;
        try {
            InetAddress ip = InetAddress.getLocalHost();
            NetworkInterface network = NetworkInterface.getByInetAddress(ip);
            if (network == null) {
                id = 1L;
            } else {
                byte[] mac = network.getHardwareAddress();
                if (null != mac) {
                    // mac地址最后两节,例如对Mac地址00:15:5d:2d:0b:01,下面的结果是id=0x0b01
                    id = ((0x000000FF & (long) mac[mac.length - 1]) | (0x0000FF00 & (((long) mac[mac.length - 2]) << 8))) >> 6;
                    // 这里是计算除以32后得到的余数
                    id = id % (maxDatacenterId + 1);
                }
            }
        } catch (Exception e) {
            logger.warn(" getDatacenterId: " + e.getMessage());
        }
        return id;
    }
    
    /**
     * 获取 maxWorkerId
     */
    protected static long getMaxWorkerId(long datacenterId, long maxWorkerId) {
        StringBuilder mpid = new StringBuilder();
        mpid.append(datacenterId);
        // 此处返回的是the name representing the running Java virtual machine
        String name = ManagementFactory.getRuntimeMXBean().getName();
        if (StringUtils.isNotBlank(name)) {
            /*
             * GET jvmPid
             */
            mpid.append(name.split(StringPool.AT)[0]);
        }
        /*
         * MAC + PID 的 hashcode 获取16个低位
         */
        return (mpid.toString().hashCode() & 0xffff) % (maxWorkerId + 1);
    }
    
    /**
     * 获取下一个 ID
     *
     * @return 下一个 ID
     */
    public synchronized long nextId() {
        long timestamp = timeGen();
        //闰秒
        if (timestamp < lastTimestamp) {
            long offset = lastTimestamp - timestamp;
            if (offset <= 5) {
                try {
                    wait(offset << 1);
                    timestamp = timeGen();
                    if (timestamp < lastTimestamp) {
                        throw new RuntimeException(String.format("Clock moved backwards.  Refusing to generate id for %d milliseconds", offset));
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            } else {
                throw new RuntimeException(String.format("Clock moved backwards.  Refusing to generate id for %d milliseconds", offset));
            }
        }

        if (lastTimestamp == timestamp) {
            // 相同毫秒内,序列号自增
            sequence = (sequence + 1) & sequenceMask;
            if (sequence == 0) {
                // 同一毫秒的序列数已经达到最大
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            // 不同毫秒内,序列号置为 1 - 3 随机数
            sequence = ThreadLocalRandom.current().nextLong(1, 3);
        }

        lastTimestamp = timestamp;

        // 时间戳部分 | 数据中心部分 | 机器标识部分 | 序列号部分
        return ((timestamp - twepoch) << timestampLeftShift)
            | (datacenterId << datacenterIdShift)
            | (workerId << workerIdShift)
            | sequence;
    }    
}
           

跟踪到这里就可以看到具体的算法了。具体来说,该算法就是Twitter的雪花算法的变种。最后生成的主键值是一个64位长整数,其具体定义如下:

最高1位未用,总为0,这样能够保证生成的主键值永远为整数;

然后是41位时间戳,其值为UTC毫秒数减去一个固定值:1288834974657L;

然后是5位datacenterId,从上面的算法来看是从主机的mac地址后2段计算出来的;

紧接着是5位的workerId,从datacenterId和pId的哈希值计算出来的;

最后是12位顺序号。也就是一毫秒时间内最多能够生成4096个主键值。

继续阅读