Spring MVC 集成EHCache缓存

废话少说,直接上代码:

ehcache.xml 文件


  
      
      
   
   
    
      
    
       
    
     

需要增加的JAR包

Spring MVC 集成EHCache缓存_第1张图片
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


   
    
    
        
    
    
        
 

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 MVC 集成EHCache缓存)