使用背景
查阅相关资料后(stack flow), Redis的expire只能作用于top-level 的key
Redis的作者Quoth Antirez:
'Hi, it is not possible, either use a different top-level key for that specific field, or store along with the filed another field with an expire time, fetch both, and let the application understand if it is still valid or not based on current time.
原链接🔗:stackoverflow.com/questions/1…
看了评论之后,有的人建议映射的ZSET上,有的人fork了下来新增了指令[ EXPIREMEMBER keyname subkey [time] ] ,也有人推荐用框架 redisson ,
但还是热评第一的做法好
给filed的value加个过期时间
每次取出来对比一下,如果已经过期,那么就删除这个field,否则就重新读取db
存:
long expirationTime = System.currentTimeMillis() + EXPIRE_TIME;
// 设置过期时间
xxxBean.setExpirationTime(Long.toString(expirationTime));
redisUtil.hSet(userIdMap, Long.toString(userId), model);
取:
Object cacheResult = redisUtil.hGet(userIdMap, userId);
if (Objects.isNull(cacheResult)) {
return null;
}
XXXBean xxxBean = JSON.to(XXXBean.class, cacheResult);
boolean ifExpired = checkIfExpire(baseAuthModel.getExpirationTime());
if (ifExpired) {
redisUtil.hDel(authUserNameMap, username);
return null;
} else {
return xxxBean;
}