业务逻辑
后端存入redis中的数据类型是值为list T的数据集合键为分类id的map,(前端是按照分类id获取数据的,当前端请求后端数据时,数据先从redis中获取,获取结果只判断是否为空,如果不为空就返回),当我们新建商品时,该分类id所对应的数据集合就会增加一条数据,如果不清楚缓存中的数据,获取到的还是新建之前的数据,当我们清除缓存后,前端会先去数据库中查询,将查询的新结果再添加到redis缓存中;修改商品时,涉及到的情况比较复杂,商品的旧分类id和新分类id,我们需要先清除旧分类id所对应的缓存数据,再清除新分类id所对应的缓存数据(这个新分类id的新,只是相对于这个商品而言,并不是对于分类而言,可能修改商品的新分类id所对应的商品数据已经存在于redis缓存之中了)
同理,删除商品时我们也需要清除该分类的redis缓存数据
查询——添加缓存
在service层注入redisTemplate对象,在业务代码中通过操作redisTemplate对象的方法实现对redis数据库的增删改查操作
redisTemplate的bean是在spring-redis.xml中创建的,交给spring容器管理。
@Autowired
private RedisTemplate redisTemplate;
先在数据库中查询数据,如果查询结果为空,再从数据库中查询,数据库中查询到结果后存入缓存中,这样下次再进行查询的时候就能从缓存中查询到
public List<TbContent> findContentByCatId(Long catId) {
List<TbContent> contents = (List<TbContent>) redisTemplate.boundHashOps("content").get(catId);
if (contents==null){
System.out.println("从数据库中读取广告信息!");
TbContentExample ex = new TbContentExample();
Criteria c = ex.createCriteria();
c.andCategoryIdEqualTo(catId);
// 1 表示启用
c.andStatusEqualTo("1");
ex.setOrderByClause("sort_order");
List<TbContent> contentList = contentMapper.selectByExample(ex);
//存入redis缓存服务器中
redisTemplate.boundHashOps("content").put(catId,contentList);
return contentList;
}else {
System.out.println("从redis缓存中读取数据!");
}
return contents;
}
新建——清除缓存
public void add(TbContent content) {
contentMapper.insert(content);
//清除缓存
redisTemplate.boundHashOps("content").delete(content.getCategoryId());
}
修改——清除缓存
public void update(TbContent content){
//清除修改前分类id(存入redis库中)
Long categoryId = contentMapper.selectByPrimaryKey(content.getId()).getCategoryId();
redisTemplate.boundHashOps("content").delete(categoryId);
contentMapper.updateByPrimaryKey(content);
if (categoryId.longValue()!=content.getCategoryId().longValue()){//分类id发生变化,清除新分类id的缓存
redisTemplate.boundHashOps("content").delete(content.getCategoryId());
}
}
删除——清除缓存
public void delete(Long[] ids) {
for(Long id:ids){
//先清除缓存
redisTemplate.boundHashOps("content").delete(contentMapper.selectByPrimaryKey(id).getCategoryId());
//后删除,如果先删除,上面的语句就查询不到了
contentMapper.deleteByPrimaryKey(id);
}
}