什么是緩存?
緩存(Cache), 就是數(shù)據(jù)交換的緩沖區(qū),俗稱(chēng)的緩存就是緩沖區(qū)內(nèi)的數(shù)據(jù),一般從數(shù)據(jù)庫(kù)中獲取,存儲(chǔ)于本地代碼。
通過(guò)Redis來(lái)緩存數(shù)據(jù),減少數(shù)據(jù)庫(kù)查詢(xún)操作;
邏輯
每個(gè)分類(lèi)的菜品保存一份緩存數(shù)據(jù)
數(shù)據(jù)庫(kù)菜品數(shù)據(jù)有變更時(shí)清理緩存數(shù)據(jù)
如何將商品數(shù)據(jù)緩存起來(lái)。
@GetMapping("/list")
@ApiOperation("根據(jù)分類(lèi)id查詢(xún)菜品")
public Result<List<DishVO>> list(Long categoryId) {
//查詢(xún)r(jià)edis里面是否存在數(shù)據(jù)類(lèi);
String key="dish_"+categoryId;
//如果存在直接返回
List<DishVO> list = (List<DishVO>) redisTemplate.opsForValue().get(key);
if (list!=null&&list.size()>0){
return Result.success(list);
}
//不存在需要查詢(xún)數(shù)據(jù)庫(kù),并保存至redis里面
Dish dish = new Dish();
dish.setCategoryId(categoryId); //設(shè)置套餐的id
dish.setStatus(StatusConstant.ENABLE);//查詢(xún)起售中的菜品
list = dishService.listWithFlavor(dish);
redisTemplate.opsForValue().set(key,list); //將他緩存起來(lái)
return Result.success(list);
}
控制臺(tái)沒(méi)有sql了,說(shuō)明緩存已經(jīng)實(shí)現(xiàn)了。
二 數(shù)據(jù)內(nèi)容發(fā)生改變的時(shí)候,需要修改redis的內(nèi)容。
修改操作、刪除菜品、起售或者停售、新建菜品也需要緩存數(shù)據(jù)
private void cleanCache(String pattern){
Set keys = redisTemplate.keys(pattern);
redisTemplate.delete(keys); //支持刪除集合的
}
刪除對(duì)應(yīng)的緩存數(shù)據(jù)
緩存套餐功能
spring Cache 實(shí)現(xiàn)了基于注解的緩存功能
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
對(duì)應(yīng)的maven坐標(biāo)文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-647258.html
注解開(kāi)發(fā)
Cacheable 在方法執(zhí)行前查詢(xún)緩存是否有數(shù)據(jù);文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-647258.html
到了這里,關(guān)于8.10 用redis實(shí)現(xiàn)緩存功能和Spring Cache的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!