這段代碼主要功能是實現使用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; } } }