Spring MVC 集成EHCache缓存

废话少说,直接上代码:

ehcache.xml 文件

<?xml version="1.0" encoding="UTF-8"?>
<ehcache dynamicConfig="false" monitoring="off" updateCheck="false"  
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ehcache.xsd">  
      
    <!-- 定义缓存策略  
        eternal="false"                 // 元素是否永恒,如果是就永不过期(必须设置)  
        maxEntriesLocalHeap="1000"      // 堆内存中最大缓存对象数,0没有限制(必须设置)  
        overflowToDisk="false"          // 当缓存达到maxElementsInMemory值是,是否允许溢出到磁盘(必须设置)  
        diskPersistent="false"          // 磁盘缓存在VM重新启动时是否保持(默认为false)  
        timeToIdleSeconds="0"           // 导致元素过期的访问间隔(秒为单位). 当eternal为false时,这个属性才有效,0表示可以永远空闲,默认为0  
        timeToLiveSeconds="600"         // 元素在缓存里存在的时间(秒为单位). 0 表示永远存在不过期  
        memoryStoreEvictionPolicy="LFU" // 当达到maxElementsInMemory时,如何强制进行驱逐默认使用"最近使用(LRU)"策略,其它还有先入先出FIFO,最少使用LFU,较少使用LRU  
   -->  
   
   <!--
    1)maxElementsInMemory(正整数):在内存中缓存的最大对象数量
    2)maxElementsOnDisk(正整数):在磁盘上缓存的最大对象数量,默认值为0,表示不限制。 
    3)eternal:设定缓存对象保存的永久属性,默认为 false 。当为 true 时 timeToIdleSeconds、timeToLiveSeconds 失效。 
    4)timeToIdleSeconds(单位:秒): 对象空闲时间,指对象在多长时间没有被访问就会失效。只对eternal为false的有效。默认值0,表示一直可以访问。
    5)timeToLiveSeconds(单位:秒): 对象存活时间,指对象从创建到失效所需要的时间。只对eternal为false的有效。默认值0,表示一直可以访问。
    6)overflowToDisk:如果内存中数据超过内存限制,是否要缓存到磁盘上。 
    7)diskPersistent:是否在磁盘上持久化。指重启jvm后,数据是否有效。默认为false。 
    8)diskSpoolBufferSizeMB(单位:MB): DiskStore使用的磁盘大小,默认值30MB。每个cache使用各自的DiskStore。
    9)memoryStoreEvictionPolicy:如果内存中数据超过内存限制,向磁盘缓存时的策略。默认值LRU,可选FIFO、LFU。
        FIFO(first in first out):先进先出
        LFU(Less Frequently Used):最少被使用,缓存的元素有一个hit属性,hit值最小的将会被清除缓存。
        LRU(Least Recently Used)默认策略:最近最少使用,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清除缓存。
    10) maxEntriesLocalHeap 堆内存中最大缓存对象数 
   -->
    <diskStore path="java.io.tmpdir"></diskStore>
    <defaultCache 
        eternal="false" 
        maxEntriesLocalHeap="0" 
        timeToIdleSeconds="120" 
        timeToLiveSeconds="120"
        maxElementsInMemory="10000"
        overflowToDisk="true"
        diskPersistent="true"
    />  
    
    <cache 
        name="userCache" 
        maxEntriesLocalHeap="10000" 
    />   
    <cache
        name="studentCache"
        maxEntriesLocalHeap="10000"
    />
     
</ehcache>

需要增加的JAR包

cache.png

springmvc.xml 需要在beans增加以下

xmlns:cache="http://www.springframework.org/schema/cache"
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd

增加bean

<!-- 启用缓存注解功能(请将其配置在Spring主配置文件中) -->
<cache:annotation-driven cache-manager="cacheManager"/>   
<!-- Spring提供的基于的Ehcache实现的缓存管理器 -->    
<bean id="cacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">    
    <property name="configLocation" value="classpath:config/ehcache.xml"/>    
</bean>    
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">    
    <property name="cacheManager" ref="cacheManagerFactory"/>    
</bean> 

EHCacheUtils 操作类

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

/**
 * 操作缓存类
 * 
 * @author jiangadam
 */

public class EhcacheUtils {

    private static final String path = "/config/ehcache.xml"; // EHCache 的配置文件地址

    private CacheManager manager;

    private static EhcacheUtils ehCache;

    private EhcacheUtils(String path) {
        manager = CacheManager.create(getClass().getResource(path));
    }

    public static EhcacheUtils getInstance() {
        if (ehCache == null) {
            ehCache = new EhcacheUtils(path);
        }
        return ehCache;
    }

    /**
     * 缓存一个对象
     * 
     * @param cacheName
     *            缓存的名字
     * @param key
     *            缓存的KEY
     * @param value
     *            缓存的值
     */
    public void put(String cacheName, String key, Object value) {
        Cache cache = manager.getCache(cacheName);
        Element element = new Element(key, value);
        cache.put(element);
    }

    /**
     * 获取一个缓存的对象,没有返回NULL
     * 
     * @param cacheName
     * @param key
     * @return
     */
    public Object get(String cacheName, String key) {
        Cache cache = manager.getCache(cacheName);
        Element element = cache.get(key);
        return element == null ? null : element.getObjectValue();
    }

    public Cache get(String cacheName) {
        return manager.getCache(cacheName);
    }

    public void remove(String cacheName, String key) {
        Cache cache = manager.getCache(cacheName);
        cache.remove(key);
    }

}

PUT 写入缓存

put.png

GET 获取缓存的数据

get.png

have fun

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,991评论 19 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,970评论 6 342
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,767评论 18 399
  • 一. Java基础部分.................................................
    wy_sure阅读 3,838评论 0 11
  • 文章作者:Tyan博客:noahsnail.com 3.4 Dependencies A typical ente...
    SnailTyan阅读 4,206评论 2 7