赞
踩
Java Caching定义了五个核心接口,分别是:CachingProvider、CacheManager、Cache、Entry和Expiry。
Spring从3.1开始定义了org.springframework.cache.Cache和org.springframework.cache.CacheManager接口来统一不同的缓存技术,并支持使用JCache(JSR-107)注解简化开发。
描述 | |
---|---|
Cache | 缓存接口,定义缓存操作,实现有RedisCache、EhcacheCache、ConcurrentMapCache等 |
CacheManager | 缓存管理器,管理各种缓存(Cache)组件 |
@Cacheable | 主要针对方法配置,能够根据方法的请求参数对其结果进行缓存 |
@CacheEvict | 清空缓存 |
@CachePut | 保证方法被调用,又希望结果被缓存 |
@EnableCaching | 开启基于注解的缓存 |
keyGenerator | 缓存数据时key的生成策略 |
serialize | 缓存数据时value的序列化策略 |
@Cacheing | 指定多个缓存策略 |
Spring Boot提供的缓存自动配置都记录在CacheAutoConfiguration中,其中CacheConfigurationImportSelector最为关键,它帮助我们导入常用缓存组件,组件如下:
使用缓存时只需要导入对应的实现即可,Spring Boot自动帮我们装配。
使用Spring Boot提供的基于Map的内存级缓存
引入Spring Boot缓存场景启动器,默认导入的就是SimpleCacheConfiguration配置,是基于Map的内存级缓存
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
通过@EnableCacheing注解开启基于注解的缓存
@EnableCaching // 开启基于注解的缓存
@SpringBootApplication
public class SimpleCacheServiceApplication {
public static void main(String[] args) {
// 启动应用程序
SpringApplication.run(SimpleCacheServiceApplication.class, args);
}
}
@Cacheable:先查询缓存数据,如果存在直接取出缓存数据返回,如果不存在就执行目标方法,将方法返回值存入缓存,常用于查询数据。
属性 | 描述 |
---|---|
cacheNames | 缓存的名字 |
key | 缓存索引,默认使用方法参数值 |
keyGenerator | 缓存索引生成器,与key属性二选一 |
cacheManager | 缓存管理器 |
condition | 满足条件进行缓存 |
unless | 满足条件不进行缓存 |
sync | 是否使用异步,默认为false |
@Override
@Cacheable(cacheNames = "user", key = "#userId")
public User findUserInformationByUserId(Integer userId) {
log.info("通过用户编号查询用户信息......");
return new User(userId, "Jack", LocalDateTime.now(), true);
}
第一次调用:先查询缓存,此时缓存中不存在数据,执行目标方法后将目标方法返回数据存入缓存
第二次调用:先查询缓存,此时缓存存在数据不执行目标方法
@CachePut:每次都先执行目标方法,将方法返回值存入缓存,常用于添加数据和修改数据。
属性 | 描述 |
---|---|
cacheNames | 缓存的名字 |
key | 缓存索引,默认使用方法参数值 |
keyGenerator | 缓存索引生成器,与key属性二选一 |
cacheManager | 缓存管理器 |
condition | 满足条件进行缓存 |
unless | 满足条件不进行缓存 |
@Override
@CachePut(cacheNames = "user", key = "#user.userId")
public Boolean insertUserInformation(User user) {
log.info("业务层 - 添加用户信息......");
return true;
}
@CacheEvict:在执行目标方法之后清除缓存,也可以指定在执行目标方法之前清除缓存,常用于删除数据。
属性 | 描述 |
---|---|
cacheNames | 缓存的名字 |
key | 需要清除缓存的索引,默认使用方法参数值 |
keyGenerator | 缓存索引生成器,与key属性二选一 |
cacheManager | 缓存管理器 |
condition | 满足条件进行清除缓存 |
allEntries | 是否清除全部缓存,默认为false |
beforeInvocation | 是否在目标方法执行之前清除缓存,默认为false |
@Override
@CacheEvict(cacheNames = "user", key = "#userId")
public Boolean deleteUserInformationByUserId(Integer userId) {
log.info("业务层 - 删除用户信息......");
return true;
}
@Caching:方法级注解,可以指定复杂的缓存策略。
@CacheConfig:类级注解,配置该类缓存策略的一些公共属性,比如缓存名称、缓存管理器、缓存索引生成策略
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。