解决多节点部署下雪花算法ID重复的问题



/**
 * 初始化雪花工具类workId及datacenterId;
 * 通过redis作为项目集群下唯一主键中心
 */
@Component
@SuppressWarnings("all")
@AutoConfigureAfter(value = {RedissonService.class})
public class SnowWorkAutoConfig implements InitializingBean {

    public SnowWorkAutoConfig(RedisTemplate<String,String> redisTemplate) {
        this.hashOperations = redisTemplate.opsForHash();
    }

    HashOperations<String,String,Integer> hashOperations;

    private  long maxWorkId;

    private long maxDatacenterId;

    private final String redisKey = RedisConstant.SNOW_SERVICE_ID;



    public void init() {
        try {
            maxWorkId = getLong("maxWorkerId");
            maxDatacenterId = getLong("maxDatacenterId");
        }catch (Exception e){
            maxWorkId = 31L;
            maxDatacenterId = 31L;
        }
        String redissonKey = redisKey + ":LOCK";
        RedissonUtil.safeRun(redissonKey,()->{
            Result result = nextId();
            new SnowflakeUtil(result.workId, result.dataCenterId);
        });
    }


    /**
     * @param filedName 字段名
     * @return SnowflakeUtil 里面的参数值
     */
    private long getLong(String filedName) throws NoSuchFieldException, IllegalAccessException {
        Field declaredField = SnowflakeUtil.class.getDeclaredField(filedName);
        declaredField.setAccessible(true);
        return declaredField.getLong(null);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        init();
    }

    static class Result {
        long workId;
        long dataCenterId;
        public Result(long workId, long dataCenterId) {
            this.workId = workId;
            this.dataCenterId = dataCenterId;
        }
    }


    /**如果 Hash 已存在,判断 dataCenterId、workerId 是否等于最大值 31,
     * 满足条件初始化 dataCenterId、workerId 设置为 0 返回
     dataCenterId 和 workerId 的排列组合一共是 1024,在进行分配时,先分配 workerId
     判断 workerId 是否 != 31,条件成立对 workerId 自增,并返回;
     如果 workerId = 31,自增 dataCenterId 并将 workerId 设置为 0
     dataCenterId、workerId 是一直向下推进的*/
    private Result nextId(){
        int defaultValue = 0;
        String dataKey = "dataCenterId";
        String workKey = "workId";
        Supplier<Result> defaultReturn = ()->{
            hashOperations.put(redisKey, dataKey,defaultValue);
            hashOperations.put(redisKey, workKey,defaultValue);
            return new Result(defaultValue, defaultValue);
        };
        if(hashOperations.hasKey(redisKey, workKey)){
            long workV = hashOperations.get(redisKey, workKey);
            long dataV = hashOperations.get(redisKey, dataKey);
            long delta = 1;
            if(workV>=maxWorkId){
                if(dataV>=maxDatacenterId){
                    return defaultReturn.get();
                }else {
                    hashOperations.put(redisKey, workKey,defaultValue);
                    return new Result(defaultValue, hashOperations.increment(redisKey, dataKey, delta));
                }
            }else {
                return new Result(hashOperations.increment(redisKey, workKey, delta),dataV);
            }
        }
        return defaultReturn.get();
    }

}
public class RedissonUtil {

    private static volatile RedissonService redissonService;

    public static RedissonService getRedissonService() {
        if(redissonService==null){
            synchronized (RedissonUtil.class){
                if(redissonService==null){
                    redissonService = SpringBeanUtils.getBean(RedissonService.class);
                }
            }
        }
        return redissonService;
    }

    public static void safeRun(String key,Runnable runnable){
        safeRun(key,5*60,3*60,runnable);
    }


    /**
     * @param key lock key
     * @param waitTime 等待时长 秒
     * @param leaseTime 自动释放时长 秒
     * @param runnable 锁内方法体
     */
    public static void safeRun(String key,long waitTime,long leaseTime,Runnable runnable){
        try {
            if(getRedissonService().tryLock(key,waitTime,leaseTime))
                runnable.run();
        }finally {
            getRedissonService().unlock(key);
        }
    }
}
public class SnowflakeUtil {
    private static final long twepoch = 1420041600000L;
    private static final long workerIdBits = 5L;
    private static final long datacenterIdBits = 5L;
    private static final long maxWorkerId = 31L;
    private static final long maxDatacenterId = 31L;
    private static final long sequenceBits = 12L;
    private static final long workerIdShift = 12L;
    private static final long datacenterIdShift = 17L;
    private static final long timestampLeftShift = 22L;
    private static final long sequenceMask = 4095L;
    private static long workerId;
    private static long datacenterId;
    private static long sequence = 0L;
    private static long lastTimestamp = -1L;

    public SnowflakeUtil(long workerId, long datacenterId) {
        if (workerId <= 31L && workerId >= 0L) {
            if (datacenterId <= 31L && datacenterId >= 0L) {
                SnowflakeUtil.workerId = workerId;
                SnowflakeUtil.datacenterId = datacenterId;
            } else {
                throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", 31L));
            }
        } else {
            throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", 31L));
        }
    }

    public static String nextId() {
        long ret = nextLongId();
        return String.valueOf(ret);
    }

    public static synchronized long nextLongId() {
        long timestamp = timeGen();
        if (timestamp < lastTimestamp) {
            throw new RuntimeException(String.format("Clock moved backwards.  Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
        } else {
            if (lastTimestamp == timestamp) {
                sequence = sequence + 1L & 4095L;
                if (sequence == 0L) {
                    timestamp = tilNextMillis(lastTimestamp);
                }
            } else {
                sequence = 0L;
            }

            lastTimestamp = timestamp;
            return timestamp - 1420041600000L << 22 | datacenterId << 17 | workerId << 12 | sequence;
        }
    }

    protected static long tilNextMillis(long lastTimestamp) {
        long timestamp;
        for(timestamp = timeGen(); timestamp <= lastTimestamp; timestamp = timeGen()) {
        }

        return timestamp;
    }

    protected static long timeGen() {
        return System.currentTimeMillis();
    }
}

最后这个是项目内用到的雪花生成Util,请根据自己的项目情况进行灵活调整

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
节点部署一致性问题是指在分布式系统中,由于多个节点同时处理请求并维护各自的数据副本,可能导致数据不一致的情况。在多节点部署中,确保数据的一致性是一个重要的挑战。 以下是一些常见的多节点部署一致性问题和相应的解决方法: 1. 数据复制延迟:当一个节点更新数据后,由于网络延迟等原因,其他节点上的数据副本可能无法立即更新。这可能导致读取操作在不同节点上获得不同的结果。解决方法包括使用同步复制和异步复制策略,以及合理设置数据复制的延迟限制。 2. 冲突解决:当多个节点同时更新同一个数据副本时,可能会发生冲突。例如,两个节点同时对同一条记录进行修改。解决方法包括使用乐观并发控制(Optimistic Concurrency Control)和悲观并发控制(Pessimistic Concurrency Control)等技术来处理并发冲突。 3. 一致性协议:为了确保多个节点之间的数据一致性,需要使用一致性协议,如Paxos、Raft、ZAB等。这些协议通过引入一致性约束和选举机制来保证节点之间的数据一致性。 4. 故障恢复:在多节点部署中,节点可能会发生故障导致数据不一致。解决方法包括使用故障检测和恢复机制,如心跳检测、故障转移和数据修复等。 5. 并发控制:多节点部署中可能存在并发读写操作,需要合理控制并发访问,以避免数据不一致。常见的并发控制方法包括锁机制、事务隔离级别和乐观并发控制等。 综上所述,多节点部署一致性问题需要综合考虑数据复制延迟、冲突解决、一致性协议、故障恢复和并发控制等因素,以确保分布式系统的数据一致性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

来自远方的猪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值