使用Redis 计数器防止刷接口

        业务需求中经常有需要用到计数器的场景:为了防止恶意刷接口,需要设置一个接口每个IP一分钟、一天等的调用次数阈值;为了降低费用,限制发送短信的次数等。使用Redis的Incr自增命令可以轻松实现以上需求,而且避免验证码带来的弊端,如不够人性化,用户操作时间长、体验差等。以一个接口每个IP每分钟限制调用100次为例:

复制代码
    private boolean isDenied(String ip){

         SimpleDateFormat sdf = new SimpleDateFormat("YYYYMMDDHHmm");
         String time = sdf.format(Calendar.getInstance().getTime());

         long count=JedisUtil.setIncr(time +"_"+ip+"_IP", 86400);

       if(count<=100){
            return false;
        }
        return true;
    }
复制代码
复制代码
public class JedisUtil {
    protected final static Logger logger = Logger.getLogger(JedisUtil.class);
    private static  JedisPool jedisPool;
    
    @Autowired(required = true)
    public void setJedisPool(JedisPool jedisPool) {
        JedisUtil.jedisPool = jedisPool;
    }
    /**
     * 对某个键的值自增
     * @author Wiener
     * @param key 键
     * @param cacheSeconds 超时时间,0为不超时
     * @return
     */
    public static long setIncr(String key, int cacheSeconds) {
        long result = 0;
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            result =jedis.incr(key);
            if (cacheSeconds != 0) {
             jedis.expire(key, cacheSeconds);
            }
            logger.debug("set "+ key + " = " + result);
        } catch (Exception e) {
            logger.warn("set "+ key + " = " + result);
        } finally {
            jedisPool.returnResource(jedis);
        }
        return result;
    }
}    
复制代码

参考文献:https://blog.csdn.net/qq_33556185/article/details/79427271

 

posted @   楼兰胡杨  阅读(1920)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
点击右上角即可分享
微信分享提示