專業(yè)的聊城網(wǎng)站建設什么是seo搜索優(yōu)化
個人簡介:Java領域新星創(chuàng)作者;阿里云技術博主、星級博主、專家博主;正在Java學習的路上摸爬滾打,記錄學習的過程~
個人主頁:.29.的博客
學習社區(qū):進去逛一逛~
Spring Cache框架
- 簡介
- Spring Cache 環(huán)境準備
- Spring Cache 常用注解使用
簡介
- Spring Cache是一個框架,實現(xiàn)了基于注解的緩存功能,只需要簡單地加一個注解,就能實現(xiàn)緩存功能。Spring Cache提供了一層抽象,底層可以切換不同的cache實現(xiàn)。具體就是通過
CacheManager
接口來統(tǒng)一不同的緩存技術。
CacheManager是Spring提供的各種緩存技術抽象接口。
針對不同的緩存技術需要實現(xiàn)不同的CacheManager:
Spring Cache 環(huán)境準備
maven依賴導入:
<!--緩存依賴--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-cache</artifactId></dependency><!--redis依賴--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency>
yml配置文件
:
spring:cache:redis: # 設置redis緩存time-to-live: 1800000 #設置緩存過期時間,可選
開啟緩存功能
:
- 在啟動類上使用@EnableCache注解
@Slf4j
@SpringBootApplication
@EnableCaching //開啟緩存
public class CacheDemoApplication {public static void main(String[] args) {SpringApplication.run(CacheDemoApplication.class,args);log.info("項目啟動成功...");}
}
操作緩存
:
- 在Controller層的方法上使用**@Cacheable、@CacheEvict、@CachePut**等注解,進行緩存操作。
Spring Cache 常用注解使用
在spring boot項目中,使用緩存技術只需在項目中導入相關緩存技術的依賴包,并在啟動類上使用@EnableCaching
開啟緩存支持即可。
- @EnableCaching
- @Cacheable
- @CachePut
- @CacheEvict
-
可使用用于動態(tài)計算密鑰的Spring Expression Language (SpEL)表達式。
-
#result
表示方法調用結果的引用。 -
#root.method
,#root.target
, 和#root.caches
分別用于引用方法、目標對象和受影響的緩存的緩存。 -
方法名(
#root.methodName
)和目標類(#root.targetClass
) -
方法參數(shù)可以通過索引訪問。例如,第二個參數(shù)可以通過
#root
訪問:#root.args [1]
,#p1
或#a1
。如果信息可用,也可以通過名稱訪問參數(shù)
@CachePut注解 案例
:
/*** CachePut:將方法返回值放入緩存* value:緩存的名稱,每個緩存名稱下面可以有多個key* key:緩存的key*/@CachePut(value = "userCache",key = "#user.id")@PostMappingpublic User save(User user){userService.save(user);return user;}
@CacheEvict注解 案例
/*** CacheEvict:清理指定緩存* 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注解 案例
/*** Cacheable:在方法執(zhí)行前spring先查看緩存中是否有數(shù)據(jù),如果有數(shù)據(jù),則直接返回緩存數(shù)據(jù);若沒有數(shù)據(jù),調用方法并將方法返回值放到緩存中* value:緩存的名稱,每個緩存名稱下面可以有多個key* key:緩存的key* condition:條件,滿足條件時才緩存數(shù)據(jù)(無法使用#result等對象)* unless:滿足條件則不緩存*///根據(jù)id獲取信息@Cacheable(value = "userCache",key = "#id",unless = "#result == null")@GetMapping("/{id}")public User getById(@PathVariable Long id){User user = userService.getById(id);return user;}//獲取所有消息@Cacheable(value = "userCache",key = "#user.id + '_' + #user.name")@GetMapping("/list")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(queryWrapper);return list;}