91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

java中snowflake算法怎么使用

小億
83
2024-06-03 15:52:18
欄目: 編程語言

Snowflake算法是Twitter開源的分布式唯一ID生成算法,通過生成64位的唯一ID,其中包括41位的時間戳,10位的機器ID和12位的序列號。

要在Java中使用Snowflake算法,首先需要實現一個Snowflake類來生成唯一ID。以下是一個簡單的示例代碼:

public class Snowflake {
    private final long workerId;
    private final static long START_TIMESTAMP = 1577808000000L; // 2020-01-01
    private long sequence = 0L;
    private final static long WORKER_ID_BITS = 5L;
    private final static long MAX_WORKER_ID = -1L ^ (-1L << WORKER_ID_BITS);
    private final static long SEQUENCE_BITS = 12L;
    private final static long WORKER_ID_SHIFT = SEQUENCE_BITS;
    private final static long TIMESTAMP_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS;
    private final static long SEQUENCE_MASK = -1L ^ (-1L << SEQUENCE_BITS);
    private long lastTimestamp = -1L;

    public Snowflake(long workerId) {
        if (workerId > MAX_WORKER_ID || workerId < 0) {
            throw new IllegalArgumentException(String.format("Worker ID must be between 0 and %d", MAX_WORKER_ID));
        }
        this.workerId = workerId;
    }

    public synchronized long nextId() {
        long timestamp = System.currentTimeMillis();
        if (timestamp < lastTimestamp) {
            throw new RuntimeException("Clock moved backwards. Refusing to generate id");
        }

        if (timestamp == lastTimestamp) {
            sequence = (sequence + 1) & SEQUENCE_MASK;
            if (sequence == 0) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0L;
        }

        lastTimestamp = timestamp;

        return ((timestamp - START_TIMESTAMP) << TIMESTAMP_SHIFT) |
                (workerId << WORKER_ID_SHIFT) |
                sequence;
    }

    private long tilNextMillis(long lastTimestamp) {
        long timestamp = System.currentTimeMillis();
        while (timestamp <= lastTimestamp) {
            timestamp = System.currentTimeMillis();
        }
        return timestamp;
    }

    public static void main(String[] args) {
        Snowflake snowflake = new Snowflake(1);
        System.out.println(snowflake.nextId());
    }
}

在main方法中,創建一個Snowflake對象,然后調用nextId方法就可以生成唯一ID。可以根據需要調整START_TIMESTAMP、WORKER_ID_BITS和SEQUENCE_BITS等參數。

0
涿鹿县| 攀枝花市| 米林县| 胶南市| 晋州市| 丹东市| 丰原市| 晋中市| 临桂县| 蚌埠市| 博湖县| 台前县| 河北省| 井冈山市| 忻州市| 鄂州市| 体育| 睢宁县| 龙口市| 台山市| 开远市| 正蓝旗| 六安市| 柘荣县| 内黄县| 仪征市| 曲阜市| 和平县| 天长市| 玉屏| 德格县| 中江县| 徐州市| 大兴区| 洛隆县| 苍溪县| 南平市| 金昌市| 黄平县| 山东省| 武威市|