1.问题
现在存在一个问题。现在这个缓存始终是从Reds中读的
。这个时候如果在后台改了广告数据会怎么样?他是不是前台还依然读的是旧数据啊?比如在运营商后台管理中修改了某个广告的状态为无效,那么在前台依然会把这个广告先查出来。这是因为什么呢?因为和后端没关系,只是查缓存,缓存的数据并没有被更新。那么怎么样才能让缓存更新
呢?什么时候更新呢?在数据的增删改
的时候要对这个缓存进行更新。那么所谓更新其实就是把这个缓存删掉
,删掉之后它再查,缓存没有,它就会从数据库中查最新的。其实我们要用的就是一个删除缓存
,实际上更新缓存就是删除缓存。
2.代码
/**
* 新增
*/
@Override
public void add(TbContent content) {
contentMapper.insert(content);
// 清除缓存
redisTemplate.boundHashOps("content").delete(content.getCategoryId());
}
/**
* 修改
*/
@Override
public void update(TbContent content) {
// 查询原来的分组ID
Long categoryId = contentMapper.selectByPrimaryKey(content.getId()).getCategoryId();
// 清除原分组的缓存
redisTemplate.boundHashOps("content").delete(categoryId);
contentMapper.updateByPrimaryKey(content);
// 清除现分组的缓存
if(categoryId.longValue() != content.getCategoryId().longValue()) {
redisTemplate.boundHashOps("content").delete(content.getCategoryId());
}
}
/**
* 批量删除
*/
@Override
public void delete(Long[] ids) {
for (Long id : ids) {
// 清除缓存
Long categoryId = contentMapper.selectByPrimaryKey(id).getCategoryId();
redisTemplate.boundHashOps("content").delete(categoryId);
contentMapper.deleteByPrimaryKey(id);
}
}
删除大key广告下的小key广告分组ID下的所有广告。就是它加到哪个组里了,哪个组就得请一下。然后下次查的时候就会先充数据库中读取。