40分布式电商项目 - 网站首页(缓存广告数据)

代码已上传至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 blocke.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 方法

/*** 增加*/@Overridepublic void add(TbContent content) {//清空缓存redisTemplate.boundHashOps("index_cache").delete(content.getCategoryId()+"");contentMapper.insert(content);}

修改广告后清除缓存:
考虑到用户可能会修改广告的分类,这样需要把原分类的缓存和新分类的缓存都清除掉。

/*** 修改* 1,分类id也发生了变化* 2,id没法发生变化*/@Overridepublic void update(TbContent content) {//根据当前id查询广告对象TbContent tbContent = contentMapper.selectByPrimaryKey(content.getId());		//清空缓存redisTemplate.boundHashOps("index_cache").delete(tbContent.getCategoryId()+"");contentMapper.updateByPrimaryKey(content);}

删除广告后清除缓存:

/*** 批量删除*/@Overridepublic void delete(Long[] ids) {for (Long id : ids) {//查询广告内容对象TbContent content = contentMapper.selectByPrimaryKey(id);redisTemplate.boundHashOps("index_cache").delete(content.getCategoryId()+"");contentMapper.deleteByPrimaryKey(id);}}


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部