代码已上传至Github 地址:https://github.com/ylw-github/pingyougou.git 版本:8e95815be1cdc8c8edb05eed86c32fe650ea0efc
现在我们首页的广告每次都是从数据库读取,这样当网站访问量达到高峰时段,对数据库压力很大,并且影响执行效率。我们需要将这部分广告数据缓存起来。
例如轮播图,每一次都要去访问数据库,会造成数据库的压力增大,所以可以使用Redis缓存,例如下面的片段代码:
public List findContentListByCategoryId(Long categoryId) {
try {
//先查询缓存
List adList = (List) redisTemplate.boundHashOps("index_cache").get(categoryId+"");
//判断缓存数据是否存在
if(adList!=null && adList.size()>0){
return adList;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 创建广告内容表example对象
TbContentExample example = new TbContentExample();
// 创建criteria对象
Criteria createCriteria = example.createCriteria();
// 设置查询参数
// 外键
createCriteria.andCategoryIdEqualTo(categoryId);
// 查询有效广告
createCriteria.andStatusEqualTo("1");
// 设置排序字段
example.setOrderByClause("sort_order");
//执行查询
List list = contentMapper.selectByExample(example);
//添加缓存数据
redisTemplate.boundHashOps("index_cache").put(categoryId+"",list);
return list;
}
更新缓存: 当广告数据发生变更时,需要将缓存数据清除,这样再次查询才能获取最新的数据
新增广告后清除缓存: 修改 pinyougou-content-service 工程ContentServiceImpl.java 的 add 方法
/**
* 增加
*/
@Override
public void add(TbContent content) {
//清空缓存
redisTemplate.boundHashOps("index_cache").delete(content.getCategoryId()+"");
contentMapper.insert(content);
}
修改广告后清除缓存: 考虑到用户可能会修改广告的分类,这样需要把原分类的缓存和新分类的缓存都清除掉。
/**
* 修改
* 1,分类id也发生了变化
* 2,id没法发生变化
*/
@Override
public void update(TbContent content) {
//根据当前id查询广告对象
TbContent tbContent = contentMapper.selectByPrimaryKey(content.getId());
//清空缓存
redisTemplate.boundHashOps("index_cache").delete(tbContent.getCategoryId()+"");
contentMapper.updateByPrimaryKey(content);
}
删除广告后清除缓存:
/**
* 批量删除
*/
@Override
public void delete(Long[] ids) {
for (Long id : ids) {
//查询广告内容对象
TbContent content = contentMapper.selectByPrimaryKey(id);
redisTemplate.boundHashOps("index_cache").delete(content.getCategoryId()+"");
contentMapper.deleteByPrimaryKey(id);
}
}