最近使用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));
}
}

本文介绍如何在SpringCloud项目中使用Redis生成唯一ID来解决数据插入重复问题。当Redis不可用时,将采用UUID生成唯一标识。
1641

被折叠的 条评论
为什么被折叠?



