Spring4 整合配置 ehcache

ehcache用的2.6.11

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

spring用的 4.2.2.RELEASE

spring的pom我就不贴了。

下面是applicationContext.xml的配置,其他多余的配置我删掉了,只看ehcache

<?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文件,用来手动操作cache

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();
    }

 

转载于:https://my.oschina.net/u/555639/blog/890190

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值