guava LoadingCache 的用法

这段代码主要功能是实现使用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;
        }
    }
}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值