• 第二十一篇:spring怎么做缓存


     项目背景:
    你可能遇情景:
    1、一个做统计的页面,每次刷新需要调接口做查询 ,是联表查询,查出来的数据还需要做一些计算或者加工,不算页面上的图表插件,刷新一次,延迟个几秒钟才出的来
    2、 一个统计接口如此,一个页面如果好几个统计的接口查询……
    3、你有很多接口都要调用同一个方法,这个方法,正好又是耗时长的查询统计……
    总之,慢就一个字

    缓存可以解决,现在的缓存都已经很高明了,Redis这样的,以及数据库这样的不提,希望以后能遇到^-^
    在此记录下这段时间用的spring集成的ehcache
    第一步:配置spring的cacheManager
    图片

     第二步:配置ehcache.xml
    图片
    第三步:编写EhcacheUtil工具类
    /**
     * Ecache工具类
     */
    public class EhcacheUtil {
     
     private static final String path = "/ehcache/ehcache.xml"; 
     private URL url; 
     private CacheManager manager; 
     private static EhcacheUtil ehCache; 

     private EhcacheUtil(String path) { 
         url = getClass().getResource(path); 
         manager = CacheManager.create(url); 
     } 
     //静态工厂,第一次调用的时候实例化自己一遍
     public static EhcacheUtil getInstance() { 
         if (ehCache== null) { 
         ehCache= new EhcacheUtil(path); 
         }
         return ehCache; 
     } 

    //存入名为cacheName的缓存块,键值对为key-value
     public void put(String cacheName, String key, Object value) { 
         Cache cache = get(cacheName); 
         Element element = new Element(key, value); 
         cache.put(element); 
     } 

    //取出名为cacheName的缓存
    public Cache get(String cacheName) { 
        return  manager.getCache(cacheName);
     } 

     //取
     public Object get(String cacheName, String key) { 
        return   get(cacheName).get(key).getObjectValue(); 
     } 

    //删
    public void remove(String cacheName, String key) { 
          get(cacheName).remove(key);
     } 


    这样你就可以手动控制你的缓存了
    通常spring的做法是使用注解@Cached,标注这个注解的方法的返回值会被加入缓存,在下次调用的时候就可以直接从缓存中取
    但是这样有个问题,这样缓存的数据需要某个机制不断去清空缓存,让新的缓存更新进来 
    因此我使用一个定时任务,定时更新,尤其是统计类型的方法
    所以下一篇,准备讲spring的定时任务
  • 相关阅读:
    tensorflow2.0 GPU和CPU 时间对比
    第一次使用FileZilla Server
    PremiumSoft Navicat 15 for Oracle中文破解版安装教程
    Unmapped Spring configuration files found. Please configure Spring facet or use 'Create Default Context' to add one including all unmapped files.
    ng : 无法加载文件 D: odejs ode_global g.ps1,因为在此系统上禁止运行脚本。有关详细信息,请参阅 https:/go.microsoft.com/fwlink/?LinkID=135170 中的 about_Execution_Policies。
    angular
    Github上优秀的go项目
    win10---file explore 中remove quick access folder
    react--useEffect使用
    linux---cat 和 grep 的妙用
  • 原文地址:https://www.cnblogs.com/yb38156/p/9821981.html
Copyright © 2020-2023  润新知