All Downloads are FREE. Search and download functionalities are using the official Maven repository.

shz.core.id.IntIdProducer Maven / Gradle / Ivy

There is a newer version: 10.3.1
Show newest version
package shz.core.id;

import shz.core.Help;

public class IntIdProducer implements IdProducer {
    /**
     * 起始时间戳/1000,id中有效值 ,这个值的设置直接影响到id的使用年限
     */
    protected int startTimestamp = 1604764800;
    /**
     * 最后时间戳/1000,防止时钟回拨
     */
    private int lastTimestamp;

    public final void setStartTimestamp(int startTimestamp) {
        this.startTimestamp = startTimestamp;
    }

    public final void setLastTimestamp(int lastTimestamp) {
        this.lastTimestamp = lastTimestamp;
    }

    /**
     * 保存最后时间戳/1000
     */
    protected void saveLastTimestamp(int lastTimestamp) {
    }

    /**
     * 同一秒内的自增序列(0-3)
     */
    private int sequence;

    /**
     * 预支秒数
     */
    private int adviceSecond;

    public final void setAdviceSecond(int adviceSecond) {
        this.adviceSecond = adviceSecond;
    }

    protected void saveAdviceSecond(int adviceSecond) {
    }

    @Override
    public final synchronized Integer next() {
        int timestamp = (int) (System.currentTimeMillis() / 1000L) + adviceSecond;
        int delta = timestamp - lastTimestamp;
        if (delta < 0)
            throw new RuntimeException(Help.format("时钟回拨:%d秒", lastTimestamp - timestamp));
        if (delta == 0) {
            sequence = (sequence + 1) & (~(-1 << 2));
            if (sequence == 0) {
                ++adviceSecond;
                ++timestamp;
                saveAdviceSecond(adviceSecond);
                saveLastTimestamp(timestamp);
            }
        } else {
            sequence = 0;
            if (adviceSecond > 0) {
                adviceSecond = Math.max(0, adviceSecond - delta + 1);
                timestamp = (int) (System.currentTimeMillis() / 1000L) + adviceSecond;
                saveAdviceSecond(adviceSecond);
            }
            saveLastTimestamp(timestamp);
        }

        lastTimestamp = timestamp;
        return (((timestamp - startTimestamp) << 2) & Integer.MAX_VALUE) | sequence;
    }

    @Override
    public final Object analyze(Integer integer) {
        //只用于单体应用,不做解析
        return null;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy