SpringCache是一个框架,实现了基于注解的缓存功能,只需要简单的加一个注解,就可以实现缓存功能。
SpringCache提供了一层抽象,底层可以切换不同的缓存实现。例如:
EHChche
Redis
Caffeine
常用注解:
@EnableCaching 开启缓存注解功能,通常加在启动类上
@Cacheable 在方法执行前先查询缓存中是否有数据,如果有则直接返回数据,如果没有则调用方法并将方法返回值放到缓存中去
@CachePut 将方法的返回值放到缓存中去
@CacheEvice 将一条或多条数据从缓存中删除
@EnableCaching加在启动类上
package com.itheima;import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;@Slf4j
@SpringBootApplication
@EnableCaching
public class CacheDemoApplication {public static void main(String[] args) {SpringApplication.run(CacheDemoApplication.class,args);log.info("项目启动成功...");}
}
@CachePut
@PostMapping@CachePut(cacheNames = "userCache", key = "#user.id")public User save(@RequestBody User user) {userMapper.insert(user);return user;}
@Cacheable
@GetMapping@Cacheable(cacheNames = "userCache",key = "#id")public User getById(Long id){User user = userMapper.getById(id);return user;}
@CacheEvice
@DeleteMapping@CacheEvict(cacheNames = "userCache",key = "#id")public void deleteById(Long id){userMapper.deleteById(id);}
@DeleteMapping("/delAll")@CacheEvict(cacheNames = "userCache", allEntries = true)public void deleteAll() {userMapper.deleteAll();}