Spring4 整合配置 ehcache

ehcache用的2.6.11java

<dependency>
			<groupId>net.sf.ehcache</groupId>
			<artifactId>ehcache-core</artifactId>
			<version>2.6.11</version>
		</dependency>

spring用的 4.2.2.RELEASEspring

spring的pom我就不貼了。express

下面是applicationContext.xml的配置,其餘多餘的配置我刪掉了,只看ehcacheapi

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	   xmlns:context="http://www.springframework.org/schema/context"
	   xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	   xmlns:jee="http://www.springframework.org/schema/jee"
	   xmlns:tx="http://www.springframework.org/schema/tx"
	   xmlns:jpa="http://www.springframework.org/schema/data/jpa"
	   xmlns:aop="http://www.springframework.org/schema/aop"
	   xmlns:ehcache="http://www.springframework.org/schema/cache"
	   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
		http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
		http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
		http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
		http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd"
	   default-lazy-init="true">

	<description>Spring公共配置</description>

	<!-- 使用annotation 自動註冊bean, 並保證@Required、@Autowired的屬性被注入 -->
	<context:component-scan base-package="com.test.*">
		<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
	</context:component-scan>



	<!-- 定義CacheManager -->
	<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
		<!-- 指定配置文件的位置 -->
		<property name="configLocation" value="classpath:ehcache/ehcache.xml"/>
		<!-- 指定新建的CacheManager的名稱 -->
		<property name="cacheManagerName" value="cacheManagerName"/>
	</bean>

</beans>

新建一個ehcache.xml文件緩存

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">

    <defaultCache eternal="false"
                  maxElementsInMemory="100000"
                  overflowToDisk="false"
                  diskPersistent="false"
                  timeToIdleSeconds="86400"
                  timeToLiveSeconds="86400"
                  memoryStoreEvictionPolicy="FIFO" />

    <!-- 登陸記錄緩存 鎖定10分鐘 -->
    <cache name="wxApiPasswordRetryCache"
           eternal="false"
           maxElementsInMemory="100000"
           overflowToDisk="false"
           diskPersistent="false"
           timeToIdleSeconds="600"
           timeToLiveSeconds="600"
           memoryStoreEvictionPolicy="FIFO" />

    <!--
        name:緩存名稱。
        maxElementsInMemory:緩存最大個數。
        eternal:對象是否永久有效,一但設置了,timeout將不起做用。
        timeToIdleSeconds:設置對象在失效前的容許閒置時間(單位:秒)。僅當eternal=false對象不是永久有效時使用,可選屬性,默認值是0,也就是可閒置時間無窮大。
        timeToLiveSeconds:設置對象在失效前容許存活時間(單位:秒)。最大時間介於建立時間和失效時間之間。僅當eternal=false對象不是永久有效時使用,默認是0.,也就是對象存活時間無窮大。
        overflowToDisk:當內存中對象數量達到maxElementsInMemory時,Ehcache將會對象寫到磁盤中。
        diskSpoolBufferSizeMB:這個參數設置DiskStore(磁盤緩存)的緩存區大小。默認是30MB。每一個Cache都應該有本身的一個緩衝區。
        maxElementsOnDisk:硬盤最大緩存個數。
        diskPersistent:是否緩存虛擬機重啓期數據 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.
        diskExpiryThreadIntervalSeconds:磁盤失效線程運行時間間隔,默認是120秒。
        memoryStoreEvictionPolicy:當達到maxElementsInMemory限制時,Ehcache將會根據指定的策略去清理內存。默認策略是LRU(最近最少使用)。你能夠設置爲FIFO(先進先出)或是LFU(較少使用)。
        clearOnFlush:內存數量最大時是否清除。
    -->

</ehcache>

新建一個EhCacheUtil文件,用來手動操做cacheapp

package com.test.util;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.ehcache.EhCacheManagerFactoryBean;
import org.springframework.stereotype.Component;

/**
 * EhCache管理工具
 * @author jason
 */
@Component
public class EhCacheUtil {
    @Autowired
    private EhCacheManagerFactoryBean ehCacheManagerFactoryBean;
    private CacheManager cacheManager;

    /**登陸錯誤次數cache*/
    private final String CACHE_NAME_WX = "wxApiPasswordRetryCache";

    public void putWXErrorNum(Object cacheKey, Object cacheValue){
        put(CACHE_NAME_WX,cacheKey,cacheValue);
    }

    public int getWXErrorNum(Object cacheKey){
        Integer errorNum = (Integer) get(CACHE_NAME_WX,cacheKey);
        return errorNum==null ? 0 : errorNum;
    }

    public boolean removeWXErrorNum(Object cacheKey) {
        Cache cache = getCacheManager().getCache(CACHE_NAME_WX);
        return cache.remove(cacheKey);
    }

    /**
     * 存儲緩存,添加版本
     * @param cacheName 緩存名稱
     * @param cacheKey 緩存鍵
     * @param cacheValue 緩存值
     * @param version 緩存版本
     */
    public void put(String cacheName, Object cacheKey, Object cacheValue, long version) {
        Cache cache = getCacheManager().getCache(cacheName);
        Element element = new Element(cacheKey, cacheValue, version);
        cache.put(element);
    }

    /**
     * 存儲緩存,使用默認版本
     * @param cacheName 緩存名稱
     * @param cacheKey 緩存鍵
     * @param cacheValue  緩存值
     */
    public void put(String cacheName, Object cacheKey, Object cacheValue) {
        put(cacheName, cacheKey, cacheValue, 1L);
    }

    /**
     * 換取緩存對象
     * @param cacheName 緩存名稱
     * @param cacheKey 緩存鍵
     * @return 返回指定緩存對象
     */
    public Object get(String cacheName, Object cacheKey) {
        Cache cache = getCacheManager().getCache(cacheName);
        Element element = cache.get(cacheKey);
        if (null == element)
        {
            return null;
        }
        return element.getObjectValue();
    }

    /**
     * 刪除緩存
     * @param cacheName 緩存名稱
     * @param cacheKey 緩存鍵
     * @return
     */
    public boolean remove(String cacheName, Object cacheKey) {
        Cache cache = getCacheManager().getCache(cacheName);
        return cache.remove(cacheKey);
    }

    /**
     * 獲取EhCache管理者
     * @return
     */
    public CacheManager getCacheManager() {
        return ehCacheManagerFactoryBean.getObject();
    }

}

在service層和controller層,能夠使用註解的方式來使用這個工具類工具

@Autowired
private EhCacheUtil ehCacheUtil;


    @RequestMapping(value="/login",method = RequestMethod.POST)
    public ResultObject login(
            @ApiParam(required = true, value = "登陸名")@RequestParam String loginName,
            @ApiParam(required = true, value = "密碼")@RequestParam String password,
            HttpServletResponse response,
            HttpServletRequest request) {
        //response.addHeader("Access-Control-Allow-Origin","*");
        //response.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
        //response.addHeader("Access-Control-Allow-Headers", "Origin, Content-Type, X-Auth-Token");

	    if(!StringKit.notBlank(loginName,password)){ return new ErrorResult("請求信息錯誤"); }
        int errorNum = ehCacheUtil.getWXErrorNum(loginName);
        if(errorNum>=5){ return new ErrorResult("登陸失敗屢次,帳戶被鎖定10分鐘"); }

        UserInfo userInfo = userInfoService.apiLogin(loginName, password);
        if(userInfo==null){
            ehCacheUtil.putWXErrorNum(loginName, errorNum + 1);
            return new ErrorResult("登陸失敗");
        }
        //登陸成功
        ehCacheUtil.removeWXErrorNum(loginName);
        return new ResultObject();
    }
相關文章
相關標籤/搜索