有个需求需要生成不重复4位数字编号,格式是 天 + 4位数字。废话不多说直接上代码
public String generate(String key) {
String redisKey = "code:" + DateUtil.format(new Date(),"dd");
//获取缓存中未被使用的编号
List values = redisCache.getCacheObject(redisKey);
if(CollectionUtil.isEmpty(values)){
//缓存中的数据为空 则生成0000- 9999放到缓存
values = new ArrayList<>();
int i = 0;
while (i <= 9999){
values.add(String.format("%1$04d", i));
i++;
}
}
//生成0 ~ values长度 随机数
Random random = new Random();
int index = random.nextInt(values.size() - 1);
String code = values.get(index);
//删除已经使用的编号 更新到缓存中
values.remove(index);
redisCache.setCacheObject(redisKey, values,1, TimeUnit.DAYS);
return code;
}



