SpringDataRedis(一)(简介)SpringDataRedis(二)(案例)(网站首页-缓存广告数据)

一、需求分析

现在我们首页的广告每次都是从数据库读取,这样当网站访问量达到高峰时段,对数据库压力很大,并且影响执行效率。我们需要将这部分广告数据缓存起来。

二、读取缓存

2.1公共组件层
因为缓存对于我们整个的系统来说是通用功能。广告需要用,其它数据可能也会用到,所以我们将配置放在公共组件层(common)中较为合理。
创建配置文件
将资源中的applicationContext-redis.xml 拷贝至common项目的src/main/resource/spring目录下
redis-config.properties拷贝到common项目的src/main/resource/properties目录下
2.2后端服务实现层
修改sellergoods-service的ContentServiceImpl

@Autowired
private RedisTemplate redisTemplate;
@Override
public List<TbContent> findByCategoryId (Long categoryId){
    List<TbContent> contentList = (List<TbContent>) redisTemplate.boundHashOps("content").get(categoryId);
    if (contentList == null) {
        System.out.println("从数据库读取数据放入缓存");
        //根据广告分类ID查询广告列表		
        TbContentExample contentExample = new TbContentExample();
        Criteria criteria2 = contentExample.createCriteria();
        criteria2.andCategoryIdEqualTo(categoryId);
        criteria2.andStatusEqualTo("1");//开启状态
        contentExample.setOrderByClause("sort_order");//排序
        contentList = contentMapper.selectByExample(contentExample);//获取广告列表
        redisTemplate.boundHashOps("content").put(categoryId, contentList);//存入缓存 
    } else {
        System.out.println("从缓存读取数据");
    }
    return contentList;
}

三、更新缓存

当广告数据发生变更时,需要将缓存数据清除,这样再次查询才能获取最新的数据
3.1新增广告后清除缓存
修改sellergoods-service工程ContentServiceImpl.java 的add方法

//    增加
@Override
public void add(TbContent content) {
    contentMapper.insert(content);
    //清除缓存
    redisTemplate.boundHashOps("content").delete(content.getCategoryId());
}

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

// 修改
@Override
public void update(TbContent content) {
    //查询修改前的分类Id
    Long categoryId = contentMapper.selectByPrimaryKey(content.getId()).getCategoryId();
    redisTemplate.boundHashOps("content").delete(categoryId);
    contentMapper.updateByPrimaryKey(content);
    //如果分类ID发生了修改,清除修改后的分类ID的缓存
    if (categoryId.longValue() != content.getCategoryId().longValue()) {
        redisTemplate.boundHashOps("content").delete(content.getCategoryId());
    }
}

3.3 删除广告后清除缓存

// 批量删除
@Override
public void delete(Long[] ids) {
    for (Long id : ids) {
        //清除缓存
        Long categoryId = contentMapper.selectByPrimaryKey(id).getCategoryId();//广告分类ID
        redisTemplate.boundHashOps("content").delete(categoryId);
        contentMapper.deleteByPrimaryKey(id);
    }
}