注:springcache並非springboot特有的功能
一、創建項目並導入依賴
<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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
Springboot2.1.5之后版本遠程連接redis時必須要加入spring-security依賴
二、相關配置和代碼
Application.properites
spring.redis.host=192.168.21.134
spring.redis.port=6379
spring.redis.database=0
spring.redis.password=520hufei520
spring.cache.cache-names=c1
spring.cache.cache-names=c1,c2…. 表示啟動時創建緩存名稱,用逗號分隔表示多個緩存名
創建pojo、service用來測試
注:使用緩存需要在springboot啟動類加上
@EnableCaching以用來開啟緩存
當方法只有一個參數時,默認緩存的key是id
當方法有兩個參數時,就需要指定key
#id |
屬性名 |
#methodName |
函數名 |
#method.name |
同上 |
#caches |
使用緩存集合中作為key,例子#caches[0] |
#args |
使用參數名作為key,使用方法同上 |
#target |
當前調用對象作為key |
#target.class |
當前作用對象的class |
還可以自己定義key
這也是一種寫法
@CacheEvict
刪除的同步緩存
@CachePut
修改時的同步緩存
在每個方法都定義一個緩存名似乎也很麻煩,可以其中定義在類上