2019-08-07|2019-08-07 Spring cache

spring cache是作用在方法上的,核心的思想是:每次调用该方法,通过传的参数和获取的结果成为键值对存入缓存中,等下次调用该方法,传入相同的参数时,直接从缓存中读取结果数据,而不会再去执行实际的查询数据库的方法。注意:在使用Spring Cache的时候我们要保证我们缓存的方法对于相同的方法参数要有相同的返回结果。
注解:@Cacheable@CacheEvict @CachePut
@Cacheable:该方法是缓存方法,允许标注在一个方法或者一个类上。当标记在某个方法上时表示该方法支持缓存,标记在类上表示该类中的所有方法都支持缓存。
该方法的几个参数,value代表要缓存的名称,value属性是必须的;key指定Spring缓存方法的返回结果时对应的key的,该属性支持SpringEL表达式,有自定义和默认两种方式;condition属性指定发生的条件,比如我们有时候不是希望缓存所有的结果。
例子:
@Cacheable(value="https://www.it610.com/article/users", key="#id")
public User find(Integer id) {
returnnull;
}
@Cacheable(value="https://www.it610.com/article/users", key="#p0")
public User find(Integer id) {
returnnull;
}
@Cacheable(value="https://www.it610.com/article/users", key="#user.id")
public User find(User user) {
returnnull;
}
@Cacheable(value="https://www.it610.com/article/users", key="#p0.id")
public User find(User user) {
returnnull;
}
Spring还为我们提供了一个root对象可以用来生成key
2019-08-07|2019-08-07 Spring cache
文章图片


@CacheEvict:该方法是清除方法,即清除缓存中的数据
allEntries属性:allEntries是boolean类型,表示是否需要清除缓存中的所有元素。默认为false,表示不需要。
@CacheEvict(value="https://www.it610.com/article/users", allEntries=true)
public void delete(Integer id) {
System.out.println("delete user by id: " + id);
}
beforeInvocation属性 :beforeInvocation可以改变触发清除操作的时间,当我们指定该属性值为true时,Spring会在调用该方法之前清除缓存中的指定元素。
@CacheEvict(value="https://www.it610.com/article/users", beforeInvocation=true)
public void delete(Integer id) {
System.out.println("delete user by id: " + id);
}
【2019-08-07|2019-08-07 Spring cache】@CachePut:与@Cacheable相同点都是缓存方法,不同点是@Cacheable只执行一次后,以后传入想通参数不在执行,而@CachePut是每次都执行该方法

    推荐阅读