Spring+Ehcache实现账户锁定

Spring整合Ehcache

  • 一、整合Ehcache

一、整合Ehcache

1、需要echache的jar包可以直接去maven仓库下载

<dependency>
	<groupId>net.sf.ehcache</groupId>
	<artifactId>ehcache</artifactId>
	<version>2.8.2</version>
</dependency>

2、需要配置文件ehcache.xml进行配置

3、修改配置文件ehcache.xml ,例如添加配置如下:




    
    
    
    
     
            eternal="false"  
            timeToIdleSeconds="3600"  
            timeToLiveSeconds="7200"  
            overflowToDisk="false"/>  
 
     
            maxElementsInMemory="10000"
            overflowToDisk="true"  
            eternal="false"
            memoryStoreEvictionPolicy="LRU"  
            maxElementsOnDisk="10000000"
            diskExpiryThreadIntervalSeconds="600"
            timeToIdleSeconds="3600"
            timeToLiveSeconds="100000"
            diskPersistent="false" />      

这里就建立了三种缓存形式

4、可以建立一个或者多个独立的类,用于对应配置文件中的配置,例如:

package com.cetc32.cache;
 
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
 
public class ReportCache {
    private static ReportCache reportCache = null;
    private static Cache cache = null;
 
    //实现单例模式
    public static ReportCache getInstance() {
        if(reportCache == null) {
            reportCache = new ReportCache();
        }
        return reportCache;
    }
 
    //private Cache cache;
 
    public ReportCache() {
        String path = this.getClass().getResource("/config/ehcache.xml").getFile();
 
        CacheManager manager = CacheManager.create(path);
        cache = manager.getCache("reportCache");
    }
 
    /**
     * 设置缓存
     * @param key
     * @param o
     */
    public void setReportCache(String key, Object o) {
 
        Element element = new Element(key, o);
        cache.put(element);
 
    }
 
    /**
     * 从缓存中获得结果
     * @param key
     * @return
     */
    public Object getReportCache(String key) {
        Element aa = cache.get(key);
        Object r = null;
        if (aa != null) {
            r = aa.getObjectValue();
        }
        return r;
 
    }
 
    /**
     * 清除某个缓存
     * @param key
     */
    public boolean removeReportCache(String key) {
        return cache.remove(key);
    }
 
    /**
     * 清空全部缓存
     */
    public void removeAllReportCache() {
        cache.removeAll();
    }
 
    /**
     * @return the cache
     */
    public Cache getCache() {
        return cache;
    }
 
}

这里采用的是单例模式,应用中一个实例即可

6、在程序中使用 ReportCache reportCache = ReportCache.getInstance(); 获取实例就可以进行缓存操作了。

你可能感兴趣的:(Spring,spring,java,后端,Ehcache,安全)