一象浑、關于Spring Cache
緩存在現(xiàn)在的應用中越來越重要窖铡,
Spring從3.1開始定義了org.springframework.cache.Cache和org.springframework.cache.CacheManager接口來統(tǒng)一不同的緩存技術,并支持使用JCache(JSR-107)注解簡化我們開發(fā)衡载。
通過SpringCache搔耕,可以快速嵌入自己的Cache實現(xiàn),主要是@Cacheable痰娱、@CachePut弃榨、@CacheEvict菩收、@CacheConfig、@Caching等注解來實現(xiàn)鲸睛。
- @Cacheable:作用于方法上娜饵,用于對于方法返回結果進行緩存,如果已經(jīng)存在該緩存官辈,則直接從緩存中獲取箱舞,緩存的key可以從入?yún)⒅兄付ǎ彺娴膙alue為方法返回值拳亿。
- @CachePut:作用于方法上褐缠,無論是否存在該緩存,每次都會重新添加緩存风瘦,緩存的key可以從入?yún)⒅兄付ǘ游海彺娴膙alue為方法返回值,常用作于更新万搔。
- @CacheEvict:作用于方法上胡桨,用于清除緩存。
- @CacheConfig:作用在類上瞬雹,統(tǒng)一配置本類的緩存注解的屬性昧谊。
- @Caching:作用于方法上,用于一次性設置多個緩存酗捌。
- @EnableCaching:作用于類上呢诬,用于開啟注解功能。
二胖缤、演示示例
欲使用Spring Cache尚镰,需要先引入Spring Cache的依賴。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--Spring Cache依賴-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
然后在啟動類上哪廓,我們需要使用@EnableCaching來聲明開啟緩存狗唉。
@EnableCaching //開啟緩存
@SpringBootApplication
public class SpringbootApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootApplication.class, args);
}
}
這樣就可以使用注解來操作緩存了,創(chuàng)建CacheService類涡真,其中dataMap的Map存儲數(shù)據(jù)分俯,省去了數(shù)據(jù)庫的操作。
@Slf4j
@Service
public class CacheService {
private Map<Integer, User> dataMap = new HashMap <Integer, User>(){
{
for (int i = 1; i < 100 ; i++) {
User u = new User("code" + i, "name" + i);
put(i, u);
}
}
};
// 獲取數(shù)據(jù)
@Cacheable(value = "cache", key = "'user:' + #id")
public User get(int id){
log.info("通過id{}查詢獲取", id);
return dataMap.get(id);
}
// 更新數(shù)據(jù)
@CachePut(value = "cache", key = "'user:' + #id")
public User set(int id, User u){
log.info("更新id{}數(shù)據(jù)", id);
dataMap.put(id, u);
return u;
}
//刪除數(shù)據(jù)
@CacheEvict(value = "cache", key = "'user:' + #id")
public User del(int id){
log.info("刪除id{}數(shù)據(jù)", id);
dataMap.remove(id);
return u;
}
}
get方法模擬查詢哆料,@Cacheable用于添加緩存缸剪,set方法用于修改,@CachePut更新緩存东亦,del方法用于刪除數(shù)據(jù)杏节, @CacheEvict刪除緩存。需要注意的是,注解的value表示緩存分類拢锹,并不是指緩存的對象值谣妻。
然后在創(chuàng)建CacheApi,用于調用CacheService進行測試卒稳。
@RestController
@RequestMapping("cache")
public class CacheApi {
@Autowired
private CacheService cacheService;
@GetMapping("get")
public User get(@RequestParam int id){
return cacheService.get(id);
}
@PostMapping("set")
public User set(@RequestParam int id, @RequestParam String code, @RequestParam String name){
User u = new User(code, name);
return cacheService.set(id, u);
}
@DeleteMapping("del")
public void del(@RequestParam int id){
cacheService.del(id);
}
}
然后我們打開swagger-ui界面(http://localhost:10900/swagger-ui.html)進行測試蹋半,多次調用查詢,可以看到充坑, CacheService的get方法减江,對于同一id僅僅執(zhí)行一遍。然后再調用更新捻爷,再次get時辈灼,即可發(fā)現(xiàn)數(shù)據(jù)已經(jīng)更新,而調用del也榄,則可以清除緩存巡莹,再次查詢又會調用方法。
源碼地址:https://github.com/imyanger/springboot-project/tree/master/p20-springboot-cache