package com.wecloud.utils;

import cn.hutool.core.lang.Snowflake;
import com.wecloud.im.ws.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * 雪花算法 获取id工具类
 *
 * @author
 */
@Component
public class SnowflakeUtil {

    private static SnowflakeUtil snowflakeUtil;
    /**
     * workerId, dataCenterId动态获取
     * 12位序列号部分，支持同一毫秒内同一个节点可以生成4096个ID,  在目前一段不用做成动态获取服务器ID
     */
    private static volatile Snowflake SNOWFLAKE = null;
    @Autowired
    private RedisUtils redisUtils;

    /**
     * 多线程中加synchronized 保证不会获取重复id
     *
     * @return
     */
    public static Long getId() {

        if (SNOWFLAKE == null) {
            synchronized (SnowflakeUtil.class) {
                if (SNOWFLAKE == null) {
                    //   workerId通过redis获取
                    long workerId = snowflakeUtil.redisUtils.incr("workerId", 1);

                    // redisUtils不需要用了,释放回收掉
                    snowflakeUtil.redisUtils = null;
                    SNOWFLAKE = new Snowflake(workerId, 1L);
                }
            }
        }
        return SNOWFLAKE.nextId();
    }

    /**
     * 静态方法里调用spring注入的方法
     */
    @PostConstruct
    public void init() {
        snowflakeUtil = this;
        snowflakeUtil.redisUtils = this.redisUtils;
    }
}
