通过redis设置有效期来解决
@Transactional
public void checkRepeat(String name, String userId) {
String check_repeat = "repeat::%s::%s";
String key = String.format(check_repeat, name, userId);
boolean bool = redisTemplate.opsForValue().setIfAbsent(key, "1");
if (bool) {
redisTemplate.expire(key, 5, TimeUnit.SECONDS);
} else {
throw new RepeatException();
}
}
此篇博客介绍了如何使用Spring的@Transactional注解配合Redis的setIfAbsent方法,设置数据的有效期来检查重复记录。通过5秒过期时间,避免了冗余操作并确保数据一致性。
3682

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



