自助設計網(wǎng)站百度關鍵詞優(yōu)化公司哪家好
1、介紹:
Spring Cache 是一個框架,實現(xiàn)了基于注解的緩存功能,只需要簡單加個注解,就能實現(xiàn)緩存功能。它提供了一層抽象,底層可以切換不同的cache實現(xiàn)。具體就是通過CacheManager 接口來實現(xiàn)不同的緩存技術。
針對不同的混存技術需要實現(xiàn)不同的CacheManager:
CacheManager | 描述 |
---|---|
EhCacheCacheManager | 使用EhCache作為緩存技術 |
GuavaCacheManager | 使用Google的GuavaCache作為緩存技術 |
RedisCacheManager | 使用Redis作為緩存技術 |
2、Spring Cache常用注解
注解 | 說明 |
---|---|
@EnableCaching | 開啟緩存注解功能 |
@Cacheable | 在方法執(zhí)行前spring先查看緩存中是否有數(shù)據(jù),如果有數(shù)據(jù),則直接返回緩存數(shù)據(jù);若沒有數(shù)據(jù),調(diào)用方法并將方法返回值放到緩存中 |
@CachePut | 將方法的返回值放到緩存中 |
@CacheEvict | 將一條或者多條數(shù)據(jù)從緩存中刪除 |
在spring boot項目中,使用緩存技術只需要導入相關緩存技術的依賴包,并在啟動類上使用@EnableCaching開啟緩存支持即可。例如,使用Redis作為緩存技術,只需要導入Spring Data Redis的maven坐標即可。
比如此處@CachePut使用例子
@CachePut(value = "name",key = "#result.id")//將方法返回值放入緩存 ,SpEL方法格式獲得數(shù)據(jù)
publie User save(User user){userService.save(user);return user;}//此處value就是緩存的名稱,每個緩存下面可以有多個key//key:緩存的key
//清理指定緩存
@CacheEvict(value = "userCache",key ="#p0")//或者
@CacheEvict(value = "userCache",key ="#root.args[0]")
@CacheEvict(value = "userCache",key ="#id")
@DeleteMapping("/{id}")
public void delete(@PathVariable Long id) {userService.removeById(id);}
@Cacheable(value = "userCache" ,key = "#id",condition = "#result != null")
@GetMapping("/{id}")
public User getById(@PathVariable Long id) {
User user = userService.getById(id);
//此時有緩存則直接返回數(shù)據(jù),不會進入該方法
//當id查詢?yōu)榭諘r,也會返回null數(shù)據(jù)當做緩存,此時需要加@Cacheable中方法condition條件,返回值不為空時加入緩存
//(unless = "#result == null"),返回值為空時不緩存return user;
}
@GetMapping("/list")
@Cacheable(value = "userCache",key = "#user.id +'_'+#user.name")
public List<User> list (User user) {LambdaQueryWrapper <user> queryWrapper = new LambdaQueryWrapper<>();queryWrapper.eq(user.getId() != null,User::getId,user.getId());queryWrapper.eq(user.getName() != null,User::getName,user.getName());List<User> list = userService.list(querryWrapper):return list;
}
底層基于Map來實現(xiàn)的,此時重啟服務,緩存都會消失,下面使用Redis來做緩存技術;配置文件需要配置redis的cache同時可配置緩存有效期time-to-live。
具體實現(xiàn)思路
1、導入Spring Cache 和 Redis 相關 maven坐標
2、在application.yml中配置緩存數(shù)據(jù)的過期時間
3、在啟動類上加@EnableCaching注解,開啟緩存注解功能
4、在查詢方法上加入@Cacheable注解
5、在修改保存方法上加入@CacheEvict注解