業務邏輯
後端存入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);
}
}