zoukankan      html  css  js  c++  java
  • Spring 缓存抽象

      Spring从3.1开始定义了org.springframework.cache.Cacheorg.springframework.cache.CacheManager接口来统一不同的缓存技术;并支持使用JCache( JSR-107)注解简化开发; 

    • Cache接口为缓存的组件规范定义,包含缓存的各种操作集合;
    • Cache接口下Spring提供了各种xxxCache的实现;如RedisCache,EhCacheCache , ConcurrentMapCache等, Cache接口如下图;

        

    • 每次调用需要缓存功能的方法时,Spring会检查检查指定参数的指定的目标方法是否已经被调用过;如果有就直接从缓存中获取方法调用后的结果,如果没有就调用方法并缓存结果后返回给用户;下次调用直接从缓存中获取;
      • 使用Spring缓存抽象时需要关注以下两点,如下图

        1.确定方法需要被缓存以及他们的缓存策略

        2.从缓存中读取之前缓存存储的数据

          

    • 常用的缓存注解及参数
      • 常用的缓存注解  

        

      • 主要参数

        

      • Cache SpEL available metadata

          

        Spring 缓存抽象有缓存自动的配置类: CacheAutoConfiguration 

        下面SpringBoot的版本为 2.0.6.RELEASE

        

        这里有个@Import的注解,用于导入ImportSelector的实现类,如下图

        

        selectImports方法用于返回导入类的名称;

        

        列出所有的CacheConfiguration

        

        yml 配置中添加如下,打印匹配的自动配置类

    debug: true
    

      

        默认情况下只有SimpleCacheConfiguration匹配

     SimpleCacheConfiguration matched:
          - Cache org.springframework.boot.autoconfigure.cache.SimpleCacheConfiguration automatic cache type (CacheCondition)
          - @ConditionalOnMissingBean (types: org.springframework.cache.CacheManager; SearchStrategy: all) did not find any beans (OnBeanCondition)
    

      

        SimpleCacheConfigurationg给Spring容器注册一个ConcurrentMapCacheManager的Bean

        

        ConcurrentMapCacheManager的getCache方法

    private final ConcurrentMap<String, Cache> cacheMap = new ConcurrentHashMap<>(16);
    

      

        该方法用于获取和创建ConcurrentMapCache类型的缓存

        

        

       缓存运行流程:

         1.先进getCache方法进行缓存查询,按照cacheNames指定的名字获取

          CacheManager先获取对应的缓存,没有则创建一个对应的缓存

         2.之后进入lookup方法,使用一个key查找缓存的内容,默认key为方法的参数

     

       先进入lookup方法查询缓存

      

     

        按照某种策略生成key

        

     

     

       generateKey方法

        

     

     

      使用keyGenerator生成key

    private final KeyGenerator keyGenerator;
    

      

     

     

      默认使用SimpleKeyGenerator

      

     

      方法执行完成后,会将结果缓存到ConcurrentMap

      

      

     

      

  • 相关阅读:
    flask和tornado的区别
    tornado1
    人脸识别
    ocr:img转成pdf,pdf转成pdf
    flask2
    《个人-GIT使用方法》
    课后作业-阅读任务-阅读笔记
    课后作业-阅读任务-阅读提问
    结对-四则运算生成器-设计文档
    团队-手机备忘录-开发环境搭建过程
  • 原文地址:https://www.cnblogs.com/coder-zyc/p/12131146.html
Copyright © 2011-2022 走看看