这段代码主要功能是实现使用guava的LoadingCache记录一个ip在一段时间类反复登录失败的次数,如果超过10次则在规定时间(expiration=1800)内禁止登录(Blocked);使用方式比较简单,没事学习用的。
引入的pom文件:
<dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>22.0</version> </dependency>
Java实现代码:
package com.merce.woven.service; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import org.springframework.stereotype.Service; import javax.annotation.PostConstruct; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; @Service public class LoginAttemptService { //缓存有效期1800秒 private int expiration = 1800; private final int MAX_ATTEMPT = 10; private LoadingCache<String, Integer> attemptsCache; //服务启动的时候初始化value值为0;这样如果给的的key不存在,则能取到初始化值0 @PostConstruct private void init(){ attemptsCache = CacheBuilder.newBuilder(). expireAfterWrite(expiration, TimeUnit.SECONDS).build(new CacheLoader<String, Integer>() { public Integer load(String key) { return 0; } }); } //删除对应key的内容信息 public void loginSucceeded(String key) { attemptsCache.invalidate(key); } //每个key loginFailed一次,则对应value+1 public void loginFailed(String key) { int attempts = 0; try { attempts = attemptsCache.get(key); } catch (ExecutionException e) { attempts = 0; } attempts++; attemptsCache.put(key, attempts); } //如果给的key的value值大于了MAX_ATTEMPT 则表示blocked public boolean isBlocked(String key) { try { return attemptsCache.get(key) >= MAX_ATTEMPT; } catch (ExecutionException e) { return false; } } }