重学SpringBoot系列之Spring cache详解

x33g5p2x  于2021-12-05 转载在 Spring  
字(20.0k)|赞(0)|评价(0)|浏览(447)

为什么使用缓存

使用缓存是一个很“高性价比”的性能优化方式,尤其是对于有大量重复查询的程序来说。通常来说,在WEB后端应用程序来说,耗时比较大的往往有两个地方:一个是查数据库,一个是调用其它服务的API(因为其它服务最终也要去做查数据库等耗时操作)。

重复查询也有两种。一种是我们在应用程序中代码写得不好,写的for循环,可能每次循环都用重复的参数去查询了。这种情况,比较聪明一点的程序员都会对这段代码进行重构,用Map来把查出来的东西暂时放在内存里,后续去查询之前先看看Map里面有没有,没有再去查数据库,其实这就是一种缓存的思想。

另一种重复查询是大量的相同或相似请求造成的。比如资讯网站首页的文章列表、电商网站首页的商品列表、微博等社交媒体热搜的文章等等,当大量的用户都去请求同样的接口,同样的数据,如果每次都去查数据库,那对数据库来说是一个不可承受的压力。所以我们通常会把高频的查询进行缓存,我们称它为“热点”。

为什么使用Spring Cache

前面提到了缓存有诸多的好处,于是大家就摩拳擦掌准备给自己的应用加上缓存的功能。但是网上一搜却发现缓存的框架太多了,各有各的优势,比如Redis、Memcached、Guava、Caffeine等等。

如果我们的程序想要使用缓存,就要与这些框架耦合。聪明的架构师已经在利用接口来降低耦合了,利用面向对象的抽象和多态的特性,做到业务代码与具体的框架分离。

但我们仍然需要显式地在代码中去调用与缓存有关的接口和方法,在合适的时候插入数据到缓存里,在合适的时候从缓存中读取数据。

想一想AOP的适用场景,这不就是天生就应该AOP去做的吗?

是的,Spring Cache就是一个这个框架。它利用了AOP,实现了基于注解的缓存功能,并且进行了合理的抽象,业务代码不用关心底层是使用了什么缓存框架,只需要简单地加一个注解,就能实现缓存功能了。而且Spring Cache也提供了很多默认的配置,用户可以3秒钟就使用上一个很不错的缓存功能。

如何使用Spring Cache

使用SpringCache分为很简单的三步:加依赖,开启缓存,加缓存注解。

加依赖

gradle:

implementation 'org.springframework.boot:spring-boot-starter-cache'

maven:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

开启缓存

在启动类加上@EnableCaching注解即可开启使用缓存。

@SpringBootApplication
@EnableCaching
public class CachingApplication {

	public static void main(String[] args) {
		SpringApplication.run(CachingApplication.class, args);
	}

}

加缓存注解

在要缓存的方法上面添加@Cacheable注解,即可缓存这个方法的返回值。

@Override
@Cacheable("books")
public Book getByIsbn(String isbn) {
    simulateSlowService();
    return new Book(isbn, "Some book");
}

// Don't do this at home
private void simulateSlowService() {
    try {
        long time = 3000L;
        Thread.sleep(time);
    } catch (InterruptedException e) {
        throw new IllegalStateException(e);
    }
}

测试

@Override
public void run(String... args) {
    logger.info(".... Fetching books");
    logger.info("isbn-1234 -->" + bookRepository.getByIsbn("isbn-1234"));
    logger.info("isbn-4567 -->" + bookRepository.getByIsbn("isbn-4567"));
    logger.info("isbn-1234 -->" + bookRepository.getByIsbn("isbn-1234"));
    logger.info("isbn-4567 -->" + bookRepository.getByIsbn("isbn-4567"));
    logger.info("isbn-1234 -->" + bookRepository.getByIsbn("isbn-1234"));
    logger.info("isbn-1234 -->" + bookRepository.getByIsbn("isbn-1234"));
}

测试一下,可以发现。第一次和第二次(第二次参数和第一次不同)调用getByIsbn方法,会等待3秒,而后面四个调用,都会立即返回。

常用注解

Spring Cache有几个常用注解,分别为@Cacheable、@CachePut、@CacheEvict、@Caching、@CacheConfig。除了最后一个CacheConfig外,其余四个都可以用在类上或者方法级别上,如果用在类上,就是对该类的所有public方法生效,下面分别介绍一下这几个注解。

@Cacheable

  • value、cacheNames:两个等同的参数(cacheNamesSpring 4新增,作为value的别名),用于指定缓存存储的集合名。由于Spring 4中新增了@CacheConfig,因此在Spring 3中原本必须有的value属性,也成为非必需项了
  • key:和cacheNames共同组成一个key,非必需,缺省按照函数的所有参数组合作为key值,若自己配置需使用SpEL表达式,比如:@Cacheable(key = "#p0"):使用函数第一个参数作为缓存的key值,更多关于SpEL表达式的详细内容可参考官方文档
  • condition:缓存对象的条件,非必需,也需使用SpEL表达式,只有满足表达式条件的内容才会被缓存,比如:@Cacheable(key = "#p0", condition = "#p0.length() < 3"),表示只有当第一个参数的长度小于3的时候才会被缓存,若做此配置上面的AAA用户就不会被缓存,读者可自行实验尝试,在函数调用前进行判断,因此result这种spel里面进行判断时,永远为null.
  • unless:另外一个缓存条件参数,非必需,需使用SpEL表达式。它不同于condition参数的地方在于它的判断时机,该条件是在函数被调用之后才做判断的,所以它可以通过对result进行判断
  • keyGenerator:用于指定key生成器,非必需。若需要指定一个自定义的key生成器,我们需要去实现org.springframework.cache.interceptor.KeyGenerator接口,并使用该参数来指定。需要注意的是:该参数与key是互斥的
  • cacheManager:用于指定使用哪个缓存管理器,非必需。只有当有多个时才需要使用
  • cacheResolver:用于指定使用那个缓存解析器,非必需。需通过org.springframework.cache.interceptor.CacheResolver接口来实现自己的缓存解析器,并用该参数指定。

作用和配置方法

/** * 根据ID获取Tasklog * @param id * @return */
    @Cacheable(value = CACHE_KEY, key = "#id",condition = "#result != null")
    public Tasklog findById(String id){
        System.out.println("FINDBYID");
        System.out.println("ID:"+id);
        return taskLogMapper.selectById(id);
    }

缓存中spel表达式可取值

@CachePut

@CachePut 的作用 主要针对方法配置,能够根据方法的请求参数对其结果进行缓存,和 @Cacheable 不同的是,它每次都会触发真实方法的调用

作用和配置方法

/** * 添加tasklog * @param tasklog * @return */
    @CachePut(value = CACHE_KEY, key = "#tasklog.id")
    public Tasklog create(Tasklog tasklog){
        System.out.println("CREATE");
        System.err.println (tasklog);
        taskLogMapper.insert(tasklog);
        return tasklog;
    }

@CacheEvict

@CachEvict 的作用 主要针对方法配置,能够根据一定的条件对缓存进行清空

一般用在更新或者删除的方法上。

作用和配置方法

/** * 根据ID删除Tasklog * @param id */
    @CacheEvict(value = CACHE_KEY, key = "#id")
    public void delete(String id){
        System.out.println("DELETE");
        System.out.println("ID:"+id);
        taskLogMapper.deleteById(id);
    }

@Caching

Java注解的机制决定了,一个方法上只能有一个相同的注解生效。那有时候可能一个方法会操作多个缓存(这个在删除缓存操作中比较常见,在添加操作中不太常见)。

Spring Cache当然也考虑到了这种情况,@Caching注解就是用来解决这类情况的,大家一看它的源码就明白了。

public @interface Caching {
	Cacheable[] cacheable() default {};
	CachePut[] put() default {};
	CacheEvict[] evict() default {};
}

有时候我们可能组合多个Cache注解使用;比如用户新增成功后,我们要添加id–>user;username—>user;email—>user的缓存;此时就需要@Caching组合多个注解标签了

@Caching(put = {
@CachePut(value = "user", key = "#user.id"),
@CachePut(value = "user", key = "#user.username"),
@CachePut(value = "user", key = "#user.email")
})
public User save(User user) {
}

@CacheConfig

前面提到的四个注解,都是Spring Cache常用的注解。每个注解都有很多可以配置的属性。

但这几个注解通常都是作用在方法上的,而有些配置可能又是一个类通用的,这种情况就可以使用@CacheConfig了,它是一个类级别的注解,可以在类级别上配置cacheNames、keyGenerator、cacheManager、cacheResolver等。

例如:

所有的@Cacheable()里面都有一个value=“xxx”的属性,这显然如果方法多了,写起来也是挺累的,如果可以一次性声明完 那就省事了, 所以,有了@CacheConfig这个配置,@CacheConfig is a class-level annotation that allows to share the cache names,如果你在你的方法写别的名字,那么依然以方法的名字为准。

@CacheConfig是一个类级别的注解。

/** * 测试服务层 */
@Service
@CacheConfig(cacheNames= "taskLog")
public class TaskLogService {
 
    @Autowired  private TaskLogMapper taskLogMapper;
    @Autowired  private net.sf.ehcache.CacheManager cacheManager;
 
    /** * 缓存的key */
    public static final String CACHE_KEY   = "taskLog";
 
    /** * 添加tasklog * @param tasklog * @return */
    @CachePut(key = "#tasklog.id")
    public Tasklog create(Tasklog tasklog){
        System.out.println("CREATE");
        System.err.println (tasklog);
        taskLogMapper.insert(tasklog);
        return tasklog;
    }
 
    /** * 根据ID获取Tasklog * @param id * @return */
    @Cacheable(key = "#id")
    public Tasklog findById(String id){
        System.out.println("FINDBYID");
        System.out.println("ID:"+id);
        return taskLogMapper.selectById(id);
    }
}

自定义缓存注解

比如之前的那个@Caching组合,会让方法上的注解显得整个代码比较乱,此时可以使用自定义注解把这些注解组合到一个注解中,如:

@Caching(put = {
    @CachePut(value = "user", key = "#user.id"),
    @CachePut(value = "user", key = "#user.username"),
    @CachePut(value = "user", key = "#user.email")
})
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface UserSaveCache {
}

这样我们在方法上使用如下代码即可,整个代码显得比较干净。

@UserSaveCache
public User save(User user){}

完整应用案例

1.启动类加注解,开启缓存功能

@SpringBootApplication
@EnableCaching//开启使用缓存
public class Application {
    public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
    }
}

2.自定义一个pojo对象

@AllArgsConstructor
@NoArgsConstructor
@Data
public class Tasklog
{
    @JsonProperty("id")
    private Integer id;
    @JsonProperty("name")
    private String name;
    @JsonProperty("age")
    private Integer age;
}

3.自定义注解

@Caching(put = {
    @CachePut(value = "taskLog", key = "#tasklog.id"),
    @CachePut(value = "taskLog", key = "#tasklog.name"),
    @CachePut(value = "taskLog", key = "#tasklog.age")
})
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface CustomCache {
}

4.service层书写

/** * 测试服务层 */
@Service
//缓存中的key由cacheNames::key组成
@CacheConfig(cacheNames = "taskLog")
public class TaskLogService {

    //模拟数据库的map
    private static Map<Integer, Object> map=new ConcurrentHashMap<>();

    static
    {
     map.put(1,new Tasklog(1,"大忽悠和小朋友",18));
    }

    /** * 缓存的key */
    public static final String CACHE_KEY = "taskLog";

    /** * 添加tasklog * @param tasklog * @return */
    //触发真实方法的调用,对请求结果进行缓存处理
    @CachePut(key = "#tasklog.id")
    public Tasklog create(Tasklog tasklog) {
        System.out.println("CREATE");
        System.err.println(tasklog);
        map.put(tasklog.getId(),tasklog);
        return tasklog;
    }

    @CustomCache//自定义注解---会生成三个key
    public Tasklog createByCustom(Tasklog tasklog) {
        System.out.println("CREATE");
        System.err.println(tasklog);
        map.put(tasklog.getId(),tasklog);
        return tasklog;
    }

    /** * 根据ID获取Tasklog * @param id * @return */
    //如果缓存中有对应的key,不进行方法调用,否则进行方法调用,并缓存返回值
    @Cacheable(key = "#id")
    public Tasklog findById(Integer id)
    {
        System.out.println("FINDBYID");
        System.out.println("ret:" +  map.get(id));
        return (Tasklog) map.get(id);
    }

    /** * 根据ID删除Tasklog * @param id */
    @CacheEvict(value = CACHE_KEY, key = "#id")
    public void delete(Integer id){
        System.out.println("DELETE");
          map.remove(id);
    }
}

4.controller层

@RestController
@RequestMapping(value ="/rest")
public class TaskLogController
{
    @Autowired
    private TaskLogService taskLogService;

    /** * 添加tasklog */
    @PutMapping("task")
    public Tasklog create(Tasklog tasklog) {
     return  taskLogService.create(tasklog);
    }
    
    @PutMapping("task_C")
    public Tasklog createCustom(Tasklog tasklog) {
        return  taskLogService.createByCustom(tasklog);
    }

    /** * 根据ID获取Tasklog */
    @GetMapping("task")
    public Tasklog findById(@RequestParam Integer id) {
         return taskLogService.findById(id);
    }

    /** * 根据ID删除Tasklog */
    @DeleteMapping("task")
    public String delById(@RequestParam Integer id) {
     taskLogService.delete(id);
        return "删除成功";
    }
}

结合源码剖析注解的运行流程

前面提到的几个注解@Cacheable、@CachePut、@CacheEvict、@CacheConfig,都有一些可配置的属性。这些配置的属性都可以在抽象类CacheOperation及其子类中可以找到。它们大概是这样的关系:

负责解析每个注解的类是SpringCacheAnnotationParser类:

…每个注解都对应有响应的解析方法

那这个SpringCacheAnnotationParser是在什么时候被调用的呢?很简单,我们在这个类的某个方法上打个断点,然后debug就行了,比如parseCacheableAnnotation方法。

debug界面,可以看到调用链非常长,前面是我们熟悉的IOC注册Bean的一个流程,直到我们看到了一个叫做AbstractAutowireCapableBeanFactoryBeanFactory,然后这个类在创建Bean的时候会去找是否有Advisor。正好Spring Cache源码里就定义了这么一个Advisor:BeanFactoryCacheOperationSourceAdvisor

这个Advisor返回的PointCut是一个CacheOperationSourcePointcut,这个PointCut复写了matches方法,在里面去获取了一个CacheOperationSource,调用它的getCacheOperations方法。这个CacheOperationSource是个接口,主要的实现类是AnnotationCacheOperationSource。在findCacheOperations方法里,就会调用到我们最开始说的SpringCacheAnnotationParser了。

这样就完成了基于注解的解析。

入口:基于AOP的拦截器

那我们实际调用方法的时候,是怎么处理的呢?我们知道,使用了AOPBean,会生成一个代理对象,实际调用的时候,会执行这个代理对象的一系列的InterceptorSpring Cache使用的是一个叫做CacheInterceptor的拦截器。我们如果加了缓存相应的注解,就会走到这个拦截器上。这个拦截器继承了CacheAspectSupport类,会执行这个类的execute方法,这个方法就是我们要分析的核心方法了。

@Cacheable的sync

我们继续看之前提到的execute方法,该方法首先会判断是否是同步。这里的同步配置是用的@Cacheablesync–(sync表示是否加锁)属性,默认是false。如果配置了同步的话,多个线程尝试用相同的key去缓存拿数据的时候,会是一个同步的操作。
![在这里插入图片描述](https://img-blog.csdnimg.cn/

上图是老版本的写法,下面是最新版本的写法

private Object execute(final CacheOperationInvoker invoker, Method method, CacheAspectSupport.CacheOperationContexts contexts) {
    //判断是否是同步
        if (contexts.isSynchronized()) {
            CacheAspectSupport.CacheOperationContext context = (CacheAspectSupport.CacheOperationContext)contexts.get(CacheableOperation.class).iterator().next();
            //判断Condition是否满足条件,如果不满足,就执行方法,因此condition是在方法执行前进行判断的
            if (!this.isConditionPassing(context, CacheOperationExpressionEvaluator.NO_RESULT)) {
                return this.invokeOperation(invoker);
            }
           //尝试获取key
            Object key = this.generateKey(context, CacheOperationExpressionEvaluator.NO_RESULT);
            //生成一个cache对象
            Cache cache = (Cache)context.getCaches().iterator().next();

            try {
                return this.wrapCacheValue(method, this.handleSynchronizedGet(invoker, key, cache));
            } catch (ValueRetrievalException var10) {
                ReflectionUtils.rethrowRuntimeException(var10.getCause());
            }
        }

        this.processCacheEvicts(contexts.get(CacheEvictOperation.class), true, CacheOperationExpressionEvaluator.NO_RESULT);
        ValueWrapper cacheHit = this.findCachedItem(contexts.get(CacheableOperation.class));
        List<CacheAspectSupport.CachePutRequest> cachePutRequests = new ArrayList();
        if (cacheHit == null) {
            this.collectPutRequests(contexts.get(CacheableOperation.class), CacheOperationExpressionEvaluator.NO_RESULT, cachePutRequests);
        }

        Object returnValue;
        Object cacheValue;
        if (cacheHit != null && !this.hasCachePut(contexts)) {
            cacheValue = cacheHit.get();
            returnValue = this.wrapCacheValue(method, cacheValue);
        } else {
            returnValue = this.invokeOperation(invoker);
            cacheValue = this.unwrapReturnValue(returnValue);
        }

        this.collectPutRequests(contexts.get(CachePutOperation.class), cacheValue, cachePutRequests);
        Iterator var8 = cachePutRequests.iterator();

        while(var8.hasNext()) {
            CacheAspectSupport.CachePutRequest cachePutRequest = (CacheAspectSupport.CachePutRequest)var8.next();
            cachePutRequest.apply(cacheValue);
        }
             
        this.processCacheEvicts(contexts.get(CacheEvictOperation.class), false, cacheValue);
        return returnValue;
    }

我们来看看同步操作的源码。如果判断当前需要同步操作(1),首先会去判断当前的condition是不是符合条件(2)。这里的condition也是@Cacheable中定义的一个配置,它是一个EL表达式,比如我们可以这样用来缓存id大于1的Book:

@Override
@Cacheable(cacheNames = "books", condition = "#id > 1", sync = true)
public Book getById(Long id) {
    return new Book(String.valueOf(id), "some book");
}

如果不符合条件,就不使用缓存,也不把结果放入缓存,直接跳到5。否则,尝试获取key(3)。在获取key的时候,会先判断用户有没有定义key,它也是一个EL表达式。如果没有的话,就用keyGenerator生成一个key

@Nullable
protected Object generateKey(@Nullable Object result) {
    if (StringUtils.hasText(this.metadata.operation.getKey())) {
        EvaluationContext evaluationContext = createEvaluationContext(result);
        return evaluator.key(this.metadata.operation.getKey(), this.metadata.methodKey, evaluationContext);
    }
    return this.metadata.keyGenerator.generate(this.target, this.metadata.method, this.args);
}

我们可以用这种方式手动指定根据id生成book-1,book-2这样的key:

@Override
@Cacheable(cacheNames = "books",  sync = true, key = "'book-' + #id")
public Book getById(Long id) {
    return new Book(String.valueOf(id), "some book");
}

这里的key是一个Object对象,如果我们不在注解上面指定key,会使用keyGenerator生成的key。默认的keyGeneratorSimpleKeyGenerator,它生成的是一个SimpleKey对象,方法也很简单,如果没有入参,就返回一个EMPTY的对象,如果有入参,且只有一个入参,并且不是空或者数组,就用这个参数(注意这里用的是参数本身,而不是SimpleKey对象。否则,用所有入参包一个SimpleKey

用的是实参的值,而不是参数的名字

源码:

@Override
public Object generate(Object target, Method method, Object... params) {
    return generateKey(params);
}

/** * Generate a key based on the specified parameters. */
public static Object generateKey(Object... params) {
    if (params.length == 0) {
        return SimpleKey.EMPTY;
    }
    if (params.length == 1) {
        Object param = params[0];
        if (param != null && !param.getClass().isArray()) {
            return param;
        }
    }
    return new SimpleKey(params);
}

看到这里你一定有一个疑问吧,这里只用入参,没有类名和方法名的区别,那如果两个方法入参一样,岂不是key冲突了?

你的感觉没错,大家可以试一下这两个方法:

// 定义两个参数都是String的方法
@Override
@Cacheable(cacheNames = "books", sync = true)
public Book getByIsbn(String isbn) {
    simulateSlowService();
    return new Book(isbn, "Some book");
}

@Override
@Cacheable(cacheNames = "books", sync = true)
public String test(String test) {
    return test;
}

// 调用这两个方法,用相同的参数"test"
logger.info("test getByIsbn -->" + bookRepository.getByIsbn("test"));
logger.info("test test -->" + bookRepository.test("test"));

你会发现两次生成的key相同,然后在调用test方法的时候,控制台会报错:

Caused by: java.lang.ClassCastException: class com.example.caching.Book cannot be cast to class java.lang.String (com.example.caching.Book is in unnamed module of loader 'app'; java.lang.String is in module java.base of loader 'bootstrap')
	at com.sun.proxy.$Proxy33.test(Unknown Source) ~[na:na]
	at com.example.caching.AppRunner.run(AppRunner.java:23) ~[main/:na]
	at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:795) ~[spring-boot-2.3.2.RELEASE.jar:2.3.2.RELEASE]
	... 5 common frames omitted

Book不能强转成String,因为我们第一次调用getByIsbn方法的时候,生成的key是test,然后换成了返回值Book对象到缓存里面。而调用test方法的时候,生成的key还是test,就会取出Book,但是test方法的返回值是String,所以会尝试强转到String,结果发现强转失败。

自定义一个keyGenerator

@Component
public class MyKeyGenerator implements KeyGenerator {
    @Override
    public Object generate(Object target, Method method, Object... params) {
        return target.getClass().getName() + method.getName() + 
                Stream.of(params).map(Object::toString).collect(Collectors.joining(","));
    }
}

然后就可以在配置里面使用这个自定义的MyKeyGenerator了,再次运行程序,就不会出现上述问题。

@Override
@Cacheable(cacheNames = "books", sync = true, keyGenerator = "myKeyGenerator")
public Book getByIsbn(String isbn) {
    simulateSlowService();
    return new Book(isbn, "Some book");
}

@Override
@Cacheable(cacheNames = "books", sync = true, keyGenerator = "myKeyGenerator")
public String test(String test) {
    return test;
}

接着往下看,可以看到我们得到了一个Cache。这个Cache是在我们调用CacheAspectSupportexecute方法的时候,会new一个CacheOperationContext。在这个Context的构造方法里,会用cacheResolver去解析注解中的Cache,生成Cache对象。

默认的cacheResolverSimpleCacheResolver,它从CacheOperation中取得配置的cacheNames,然后用cacheManagerget一个Cache。这里的cacheManager是用于管理Cache的一个容器,默认的cacheManagerConcurrentMapCacheManager。听名字就知道是基于ConcurrentMap来做的了,底层是ConcurrentHashMap

那这里的Cache是什么东西呢?Cache就对“缓存容器”的一个抽象,包含了缓存会用到的get、put、evict、putIfAbsent等方法。

不同的cacheNames会对应不同的Cache对象,比如我们可以在一个方法上定义两个cacheNames,虽然也可以用value,它是cacheNames的别名,但如果有多个配置的时候,更推荐用cacheNames,因为这样具有更好的可读性。

@Override
@Cacheable(cacheNames = {"book", "test"})
public Book getByIsbn(String isbn) {
    simulateSlowService();
    return new Book(isbn, "Some book");
}

默认的Cache是ConcurrentMapCache,它也是基于ConcurrentHashMap的。

但这里有个问题,我们回到上面的execute方法的代码,发现如果设置了sync为true,它取的是第一个Cache,而没有管剩下的Cache所以如果你配置了sync为true,只支持配置一个cacheNames,如果配了多个,就会报错:

@Cacheable(sync=true) only allows a single cache on...

继续往下看,发现调用的是Cache的get(Object, Callcable)方法。这个方法会先尝试去缓存中用key取值如果取不到在调用callable函数然后加到缓存里。Spring Cache也是期望Cache的实现类在这个方法内部实现“同步”的功能。

所以我们再回过头去看Cacheablesync属性上方的注释,它写到:使用sync为true,会有这些限制:

  • 不支持unless,这个从代码可以看到,只支持了condition,没有支持unless;这个我没想清楚为什么。。。但Interceptor代码就是这样写的。
  • 只能有一个cache,因为代码就写死了一个。我猜这是为了更好地支持同步,它把同步放到了Cache里面去实现。
  • 没有不支持其它的Cache操作,代码里面写死了,只支持Cachable,我猜这也是为了支持同步。

缓存过期之后,如果多个线程同时请求对某个数据的访问,会同时去到数据库,导致数据库瞬间负荷增高。Spring4.3为@Cacheable注解提供了一个新的参数“sync”(boolean类型,缺省为false),当设置它为true时,只有一个线程的请求会去到数据库,其他线程都会等待直到缓存可用。这个设置可以减少对数据库的瞬间并发访问。

加锁 :默认是无加锁的; sync = true(加锁,解决缓存击穿)

其它操作

如果sync为false呢?

继续往下看execute的代码,大概经历了下面这些步骤:

  • 尝试在方法调用前删除缓存,这个在@CacheEvict配置的beforeInvocation,默认为false(如果为true才会在这一步删除缓存);
    尝试获取缓存;
  • 如果第2步获取不到,尝试获取Cachable的注解,生成相应的CachePutRequest;
  • 如果第2步获取到了,并且没有CachPut注解,就直接从缓存中获取值。否则,调用目标方法;
  • 解析CachePut注解,同样生成相应的CachePutRequest;
  • 执行所有的CachePutRequest;
  • 尝试在方法调用后删除缓存,如果@CacheEvict配置的beforeInvocation为false会删除缓存
  • 至此,我们就结合源码解释完了所有的配置发生作用的时机。

使用其它缓存框架

如果要使用其它的缓存框架,应该怎么做呢?

通过上面的源码分析我们知道,如果要使用其它的缓存框架,我们只需要重新定义好CacheManagerCacheResolver这两个Bean就行了。

事实上,Spring会自动检测我们是否引入了相应的缓存框架,如果我们引入了spring-data-redis,Spring就会自动使用spring-data-redis提供的RedisCacheManager,RedisCache。

如果我们要使用Caffeine框架。只需要引入Caffeine,Spring Cache就会默认使用CaffeineCacheManager和CaffeineCache。

implementation 'org.springframework.boot:spring-boot-starter-cache'
implementation 'com.github.ben-manes.caffeine:caffeine'

Spring Cache还支持各种配置,在CacheProperties类里面,里面还提供了各种主流的缓存框架的特殊配置。比如Redis的过期时间等(默认永不过期)。

private final Caffeine caffeine = new Caffeine();

private final Couchbase couchbase = new Couchbase();

private final EhCache ehcache = new EhCache();

private final Infinispan infinispan = new Infinispan();

private final JCache jcache = new JCache();

private final Redis redis = new Redis();

使用缓存带来的问题

双写不一致

使用缓存会带来许多问题,尤其是高并发下,包括缓存穿透、缓存击穿、缓存雪崩、双写不一致等问题。

其中主要聊一下双写不一致的问题,这是一个比较常见的问题,其中一个常用的解决方案是,更新的时候,先删除缓存,再更新数据库。所以Spring Cache的@CacheEvict会有一个beforeInvocation的配置。

但使用缓存通常会存在缓存中的数据和数据库中不一致的问题,尤其是调用第三方接口,你不会知道它什么时候更新了数据。但使用缓存的业务场景很多时候并不需求数据的强一致,比如首页的热点文章,我们可以让缓存一分钟失效,这样就算一分钟内,不是最新的热点排行也没关系。

占用额外的内存

这个是无可避免的。因为总要有一个地方去放缓存。不管是ConcurrentHashMap也好,Redis也好,Caffeine也好,总归是会占用额外的内存资源去放缓存的。但缓存的思想正是用空间去换时间,有时候占用这点额外的空间对于时间上的优化来说,是非常值得的。

这里需要注意的是,SpringCache默认使用的是ConcurrentHashMap,它不会自动回收key,所以如果使用默认的这个缓存,程序就会越来越大,并且得不到回收。最终可能导致OOM。

我们来模拟实验一下:

@Component
public class MyKeyGenerator implements KeyGenerator {
    @Override
    public Object generate(Object target, Method method, Object... params) {
        // 每次都生成不同的key
        return UUID.randomUUID().toString();
    }
}

//调它个100w次
for (int i = 0; i < 1000000; i++) {
    bookRepository.test("test");
}

然后把最大内存设置成20M: -Xmx20M。

我们先来测试默认的基于ConcurrentHashMap的缓存,发现它很快就会报OOM。

Exception: java.lang.OutOfMemoryError thrown from the UncaughtExceptionHandler in thread "main"

Exception: java.lang.OutOfMemoryError thrown from the UncaughtExceptionHandler in thread "RMI TCP Connection(idle)"

我们使用Caffeine,并且配置一下它的最大容量:

spring:
  cache:
    caffeine:
      spec: maximumSize=100

再次运行程序,发现正常运行,不会报错。

所以如果是用基于同一个JVM内存的缓存的话,个人比较推荐使用Caffeine,强烈不推荐用默认的基于ConcurrentHashMap的实现。

那什么情况适合用Redis这种需要调用第三方进程的缓存呢?如果你的应用程序是分布式的,一个服务器查询出来后,希望其它服务器也能用这个缓存,那就推荐使用基于Redis的缓存。

使用Spring Cache也有不好之处,就是屏蔽了底层缓存的特性。比如,很难做到不同的场景有不同的过期时间(但并不是做不到,也可以通过配置不同的cacheManager来实现)。但整体上来看,还是利大于弊的,大家自己衡量,适合自己就好。

总结

比较重要的源码类

  • CacheAutoConfiguration 缓存的自动配置
  • 例如redis看 RedisCacheConfiguration
  • CacheManager 缓存管理者
  • 例如redis看 RedisCacheManager
  • CacheProperties 缓存默认配置
  • idea搜索的方法 双击shift 或者 ctrl n

原理快速梳理

流程说明:

 CacheAutoConfiguration  =>  RedisCacheConfiguration =>
 自动配置了RedisCacheManager =>  初始化所有的缓存 => 
 每个缓存决定使用什么配置=>
 =>如果RredisCacheConfiguration有就用已有的,没有就用默认配置(CacheProperties)
 =>想改缓存的配置,只要给容器中放一个RredisCacheConfiguration即可
 =>就会应用到当前RedisCacheManager管理的所有缓存分区中

相关文章