高并发下使用Redis生成唯一id

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/heroguo007/article/details/78490278

最近使用spirngcloud来搭建分布式项目,遇到插入重复问题,决定用redis生成唯一ID来解决。

    /**
     * 获取唯一Id
     * @param key
     * @param hashKey
     * @param delta 增加量(不传采用1)
     * @return
     * @throws BusinessException
     */
    public Long incrementHash(String key,String hashKey,Long delta) throws BusinessException{
        try {
            if (null == delta) {
                delta=1L;
            }
            return redisTemplate.opsForHash().increment(key, hashKey, delta);
        } catch (Exception e) {//redis宕机时采用uuid的方式生成唯一id
            int first = new Random(10).nextInt(8) + 1;
            int randNo=UUID.randomUUID().toString().hashCode();
            if (randNo < 0) {
                randNo=-randNo;
            }
            return Long.valueOf(first + String.format("%16d", randNo));
        }
    }

猜你喜欢

转载自blog.csdn.net/heroguo007/article/details/78490278