看好了,我只操作一次
@Repository
@Slf4j
public class RedisCounterRepository {
private final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
@Autowired
private RedisTemplate<String, String> redisTemplate;
// 根据获取的自增数据,添加日期标识构造分布式全局唯一标识
public String getNumFromRedis(String changeNumPrefix) {
return getNumFromRedis(changeNumPrefix,6);
}
public String getNumFromRedis(String changeNumPrefix,int count) {
String dateStr = LocalDate.now().format(dateTimeFormatter);
Long value = incrementNum(changeNumPrefix + dateStr);
String formatStr = "%0"+count+"d";
return dateStr + String.format(formatStr,value);
}
//
private long incrementNum(String key) {
RedisConnectionFactory factory = redisTemplate.getConnectionFactory();
if (null == factory) {
log.error("Unable to connect to redis.");
}
RedisAtomicLong redisAtomicLong = new RedisAtomicLong(key, factory);
long increment = redisAtomicLong.incrementAndGet();
if (1 == increment) {
// 如果数据是初次设置,需要设置超时时间
redisAtomicLong.expire(1, TimeUnit.DAYS);
}
return increment;
}
}