maven依赖
<shiro-spring.version>1.4.0</shiro-spring.version>
<shiro-ehcache.version>1.4.0</shiro-ehcache.version>
<!-- shiro-ehcache -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>${shiro-spring.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-ehcache</artifactId>
<version>${shiro-ehcache.version}</version>
</dependency>
一、spring-ehcache配置文件
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
updateCheck="false" monitoring="autodetect"
dynamicConfig="true" >
<diskStore path="java.io.tmpdir/ehcache"/>
<defaultCache
maxElementsInMemory="50000"
eternal="false"
timeToIdleSeconds="3600"
timeToLiveSeconds="3600"
overflowToDisk="true"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"/>
<!--timeToIdleSeconds 缓存创建后未被访问销毁时间-->
<!--timeToLiveSeconds 缓存从创建到销毁时间-->
<cache name="limitRetryCache"
maxEntriesLocalHeap="5000"
eternal="false"
timeToIdleSeconds="300"
timeToLiveSeconds="0"
overflowToDisk="false"
statistics="true">
</cache>
</ehcache>
二、shiro配置文件
net.***.RetryLimitMatcher 是ehcache的配置工具类
在securityManager安全管理器中加入
<!-- 注入缓存管理器 -->
<property name="cacheManager" ref="shiroCacheManager"/>
------------------------
<!-- 缓存管理器 -->
<bean id="ehcacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="classpath:spring/shiro-ehcache.xml"/>
</bean>
<bean id="shiroCacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
<property name="cacheManager" ref="ehcacheManager"/>
</bean>
<bean id="retryLimitMatcher" class="net.***.RetryLimitMatcher">
<constructor-arg ref="shiroCacheManager"/>
</bean>
三、ehcache配置工具类
public class RetryLimitMatcher {
private static final int MAX_LOGIN_RETRY_TIMES = 5;
private Cache<String, AtomicInteger> passwordRetryCache;
public RetryLimitMatcher(CacheManager cacheManager) {
passwordRetryCache = cacheManager.getCache("limitRetryCache");
}
public void doMatch(String userTel){
AtomicInteger retryCount = passwordRetryCache.get(userTel);
if (retryCount != null){
if (retryCount.get() >= MAX_LOGIN_RETRY_TIMES) {
throw new ExcessiveAttemptsException();
}
}
}
public boolean isLocked(String userTel){
AtomicInteger num = passwordRetryCache.get(userTel);
if(null != num && num.get() > 0){
return true;
}
return false;
}
public int getRetaryNum(String userTel){
AtomicInteger num = passwordRetryCache.get(userTel);
if(null == num){
return 5;
}
return 5 - num.intValue();
}
public void removeRetary(String userTel){
passwordRetryCache.remove(userTel);
}
}
调用
调用类继承RetryLimitMatcher使用。目前我是这么使用的你也可以吧该类通过@Compoent注入到spring中由spring统一管理,调用的时候直接通过@Autowaired或者@Resource注入使用。