编程语言
首页 > 编程语言> > 分布式雪花算法生成唯一ID

分布式雪花算法生成唯一ID

作者:互联网

Hutool工具包

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.7.16</version>
</dependency>

Snowflake需自行保证单例,否则多个对象生成ID会导致重复

代码

package com.lyods.base.utils;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.net.NetUtil;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * @creator linhy
 * @date 2021-11-16
 * @descrption 获取雪花算法ID
 *
 */
public class SnowFlakeUtil {

    private final static Logger log = LoggerFactory.getLogger(SnowFlakeUtil.class);

    private static long workerId = 0;

    private volatile static Snowflake snowflake = null;
    private volatile static SnowFlakeUtil sfu = null;

    /**
     * 单例
     */
    private SnowFlakeUtil() {
    }

    public static SnowFlakeUtil getInstance() {
        if (null == sfu) {
            synchronized (SnowFlakeUtil.class) {
                if (null == sfu) {
                    sfu = new SnowFlakeUtil();
                }
            }
        }
        return sfu;
    }

    /**
     * 获取ID
     * @return
     */
    public long snowflakeId() {
        if (null == snowflake) {
            snowflake = getSnowflake();
        }
        return snowflake.nextId();
    }

    /**
     * Snowflake对象获取
     * @return
     */
    private synchronized Snowflake getSnowflake() {
        snowflake = new Snowflake();
        return snowflake;
    }

    @PostConstruct
    public void init() {
        try {
            workerId = NetUtil.ipv4ToLong(NetUtil.getLocalhostStr());
            log.info("当前机器的workId: {}", workerId);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("当前机器的workId获取失败", e);
            workerId = NetUtil.getLocalhostStr().hashCode();
        }
    }

}

线程池30线程测试

ExecutorService executorService = Executors.newFixedThreadPool(5);
        Stream.iterate(0, x -> x + 1).limit(30).forEach(x -> {
            executorService.submit(() -> {
                long id = SnowFlakeUtil.getInstance().snowflakeId();
                System.out.println(id);
            });
        });
        executorService.shutdown();

结果
在这里插入图片描述

标签:return,snowflake,SnowFlakeUtil,private,ID,算法,static,Snowflake,分布式
来源: https://blog.csdn.net/weixin_43840809/article/details/121350499