Spring在3.1版本以后开始支持缓存功能,我们简单的缓存机制就在这里了
1. 启用缓存机制,两中方式:注解和配置文件
注释:
@Component(value = "cache")
@EnableCaching
public class CacheManager {
}
配置文件的方式:
<cache:annotation-driven />
2. 缓存管理器
2.1 内置缓存管理器
SimpleCacheManager
NoOpCacheManager
ConcurrentMapCacheManager
CompositeCacheManager
EhcacheCacheManager
2.2 在3.2之后由SpringData又提供了两个缓存管理器
RedisCacheManager(来自于Spring Data Redis项目)
GemfireCacheManager(来自Spring Data Gemfire项目)
3. 使用Spring缓存机制实例
3.1 xml 文件配置
<!--xml文件引入SimpleCacheManager内置缓存器-->
<bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">
<property name="caches">
<set>
<bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean"
p:name="personCache" />
</set>
</property>
</bean>
<cache:annotation-driven />
3.2 缓存类
@Component(value = "cache")
public class CacheManager {
@Autowired
private UserTMapper userDao;
@Cacheable(value = "personCache",key="1000")
public UserT getUser(String id,String name) {
System.out.println("this is cache test");
UserT user = userDao.selectByPrimaryKey(1);
return user;
}
@CacheEvict(value="personCache",allEntries = true)
public void reload(){
}
}
3.3 测试类
@Autowired
private CacheManager cache;
@Autowired
private UserTMapper userTMapper;
@Test
public void getUserCache(){
System.out.println(cache.getUser("ggg","name"));
System.out.println(cache.getUser("ggg","name"));
}
以上就是spring调用自己的缓存来实现
@Cacheable和@CachePut都是用来填充缓存的,但是工作方式还是有所不同;
@Cacheable首先去缓存中查找条目,这里的条目就是key,如果没有写key的话,默认会用查询的参数当做key值。如果没有找到所查询的条目,调用方法并且将返回值放到缓存中。
@CachePut不会去查询条目,直接执行方法,将返回值添加到缓存中。这时候就会想,既然不去查条目,用它来干嘛?我们可以用这个注释来实时更新缓存的内容,结合@Cacheable来使用,更新完后用@Cacheable来查询,这样用就回很方便。
再详细介绍一下@Cacheable属性
属性 | 类型 | 描述 |
value | String[] | 要使用的缓存名称 |
key | String | SpEL表达式,用来计算自定义的缓存key,默认是方法的参数值 |
condition | String | SpEL表达式,如果得到的值是false,不会讲缓存应用到方法调用上,默认是ture |
unless | String | SpEL表达式,如果的到的值是true,返回值不会放到缓存中,默认是false |