配置
<!--cache-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
启动累加上@EnableCaching,开启缓存
缓存和redis不需要配置,自动使用redis
注解使用
@Slf4j
@Service
public class UserService {
private static final String USER_CACHE = "USER_CACHE";
@Cacheable(value = USER_CACHE, key = "#id")
public User get(Integer id) {
User user = new User(id, "lipo");
log.info("select user = {}", user);
return user;
}
@CachePut(value = USER_CACHE, key = "#id")
public User update(Integer id, String name) {
User user = new User(id, name);
log.info("update user = {}", user);
return user;
}
@CacheEvict(value = USER_CACHE, key = "#id")
public User delete(Integer id) {
User user = new User(id, "asdf");
log.info("delete id = {}", id);
return user;
}
}
key用spel表达式
缓存名称和key自动用双冒号连接,多个缓存可以合并
和jetCache区别,就是jetCache缓存可以设置时间,功能多点,cache不可以
原理
1.如果需要分析自动配置的原理就需要分析自动配置类:CacheAutoConfiguration,
2.这个自动配置中导入了一个类CacheConfigurationImportSelector,这个类会引入一些缓存配置类。