SpringAOP+自定义注解实现限制接口访问频率,利用滑动窗口思想Redis的ZSet(附带整个Demo)

目录

1.创建切面

2.创建自定义注解

3.自定义异常类

4.全局异常捕获

5.Controller层

 


demo的地址,自行获取《《——————————————————————————

Spring Boot整合Aop面向切面编程实现权限校验,SpringAop+自定义注解+自定义异常+全局异常捕获,实现权限验证,要求对每个接口都实现单独的权限校验

Spring Boot整合Aop面向切面编程实现权限校验,SpringAop+自定义注解+自定义异常+全局异常捕获,实现权限验证,要求对每个接口都实现单独的权限校验

背景

在日常开发中,为了保证系统稳定性,防止被恶意攻击,我们可以控制用户访问接口的频率,

 颜色部分表示窗口大小

在指定时间内,只能允许访问N次,我们将这个指定时间T,看出一个滑动的窗口宽度,Redis的zset的score为滑动窗口,在操作zset的时候,只保留窗口数据,删除其他数据

1.创建切面

package com.example.aspect;

import com.example.annotation.RequestLimiting;
import com.example.exception.ConditionException;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.operators.arithmetic.Concat;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

@Aspect
@Slf4j
@Component
public class ApiLimitedRoleAspect {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Pointcut("@annotation(com.example.annotation.RequestLimiting)")
    public void poincut() {
    }

    @Around("poincut() && @annotation(requestLimiting)")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint, RequestLimiting requestLimiting) throws Throwable {
        //获取注解参数
        long period = requestLimiting.period();
        long count = requestLimiting.count();

        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();

        //获取ip和url
        String ip = request.getRemoteAddr();
        String uri = request.getRequestURI();

        //拼接redis的key值
        String key = "reqLimiting" + uri + ip;


        ZSetOperations<String, String> zSetOperations = stringRedisTemplate.opsForZSet();

        //获取当前时间
        long curTime = System.currentTimeMillis();
        //添加当前时间
        zSetOperations.add(key, String.valueOf(curTime), curTime);
        //设置过期时间
        stringRedisTemplate.expire(key, period, TimeUnit.SECONDS);
        //删除窗口之外的值
        //这个a指的是实际窗口的范围边界,比如,我从10:00开始访问,
        //每秒访问1次,在11:12时,记录里就会有62条,此时的a表示10:12,
        //最后会删除掉10:00-10:12的所有key,留下的都10:12-11:12的key
        Long a = curTime - period * 1000;
        log.error(String.valueOf(a));
        zSetOperations.removeRangeByScore(key, 0, a);
        //设置访问次数
        Long acount = zSetOperations.zCard(key);
        if (acount > count) {
            log.error("接口拦截:{}请求超过限制频率{}次/{}s,ip为{}", uri, count, period, ip);
            throw new ConditionException("10004", "接口访问受限,请稍后");
        }
        return proceedingJoinPoint.proceed();
    }

}

2.创建自定义注解

package com.example.annotation;

import java.lang.annotation.*;

/**
*<p> </p>
*自定义注解
 * 接口访问频率
*@author panwu
*@descripion
*@date 2024/3/24 13:23
*/
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RequestLimiting {
    //窗口宽度
    long period() default  60;

    //允许访问次数
    long count() default  5;
}

 3.自定义异常类

package com.example.exception;

public class ConditionException extends RuntimeException {
    private static final long serialVersionUID = 1L;

    private String code;

//    public ConditionException(ConditionExceptionEnum conditionExceptionEnum){
//        super(conditionExceptionEnum.getDesc());
//        this.code = conditionExceptionEnum.getCode();
//    }

    public ConditionException(String code, String name) {
        super(name);
        this.code = code;
    }


    public ConditionException(String name){
        super(name);
        code="500";
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }


}

4.全局异常捕获

package com.example.exception;


import com.example.dto.Result;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
public class ComonGlobalExceptionHandler {

    @ExceptionHandler(value = ConditionException.class)
    @ResponseBody
    public Result conditionException(ConditionException e){
        return Result.fail(e.getCode(),e.getMessage());
    }
}

5.Controller层

package com.example.controller;

import com.example.annotation.RequestLimiting;
import com.example.dto.Result;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {


    @GetMapping()
    @RequestLimiting(count = 3)
    public Result get(){
        log.debug("访问成功");
        return Result.ok("访问成功");

    }
}

要知道的是,该Demo实现的是对同一用户的反复点击进行频率限制,也可用作幂等性校验,具体值需要设置,还需要考虑分布式情况,加上分布式锁

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/485661.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

uniapp 打包后缺少maps模块和share模块的解决方案

缺失maps模块 我的应用 | 高德控制台 缺失share模块 QQ互联管理中心 微信开放平台

HTTPS总结

密码学基础 在正式讲解HTTPS协议之前&#xff0c;我们首先要知道一些密码学的知识。 明文&#xff1a; 明文指的是未被加密过的原始数据。 密文&#xff1a;明文被某种加密算法加密之后&#xff0c;会变成密文&#xff0c;从而确保原始数据的安全。密文也可以被解密&#xf…

【嵌入式学习】Qtday03.24

一、思维导图 二、练习 QMovie *mv new QMovie(":/Logo/giphy (2).gif");ui->label_5->setMovie(mv);ui->label_5->setScaledContents(true);mv->start();this->setWindowIcon(QIcon(":/Logo/bdf48b5198c8417da0e4fef6b72c5657.png"));/…

dubbo项目利用反射来调用,减少配置

dubbo项目中&#xff0c;需要定义一个dubboService注解完成类的调用 DubboService(group "net-hospital", version "1.0.0", interfaceClass ReflectionService.class)如果每个需要调用的类都要定义的话显得很复杂&#xff0c;很麻烦 优化方式&#xf…

NO9 蓝桥杯单片机串口通信之进阶版

1 回顾 串口通信的代码编写结构还是与中断一样&#xff0c;不同的是&#xff1a; 初始中断函数条件涉及到串口通信相关的寄存器和定时器1相关的寄存器&#xff08;定时器1用于产生波特率&#xff09;&#xff0c;但初始条件中的中断寄存器只考虑串口通信而不考虑定时器1。 v…

Python学习(一)

Python环境下载安装 安装略 验证安装结果与编写第一个Python程序

MySQL学习笔记------SQL(1)

关系型数据库&#xff08;RDBMS&#xff09; 建立在关系模型基础上&#xff0c;由多张相互连接的二维表组成的数据库 特点&#xff1a;使用表储存数据&#xff0c;格式统一&#xff0c;便于维护 使用SQL语言操作&#xff0c;标准统一&#xff0c;使用方便 SQL通用语法 SQL…

【Java】this 与 super 关键字

目录 this 关键字基本使用 this关键字在继承中的使用 super关键字使用 super 和 this 的比较 this 关键字基本使用 this 关键字可以用来访问本类的属性、方法、构造器 this 用于区分当前类的属性和局部变量&#xff0c;this代表当前对象访问成员方法的语法&#xff1a;thi…

Kruskal最小生成树【详细解释+动图图解】【sort中的cmp函数】 【例题:洛谷P3366 【模板】最小生成树】

文章目录 Kruskal算法简介Kruskal算法前置知识sort 中的cmp函数 算法思考样例详细示范与解释kruskal模版code↓ 例题&#xff1a;洛谷P3366 【模板】最小生成树code↓完结撒花QWQ Kruskal算法简介 K r u s k a l Kruskal Kruskal 是基于贪心算法的 M S T MST MST 算法&#xff…

Vue 实现带拖动功能的时间轴

1.效果图 2. 当使用timeline-slider-vue组件时&#xff0c;你可以设置以下属性&#xff1a; date&#xff1a;用于设置时间轴滑块的初始日期&#xff0c;格式通常为 YYYY-MM-DD。 mask&#xff1a;一个布尔值&#xff0c;用于控制是否显示背景遮罩。 markDate&#xff1a;一…

Verilog刷题笔记45

题目&#xff1a;Given the finite state machine circuit as shown, assume that the D flip-flops are initially reset to zero before the machine begins. Build this circuit. 解题&#xff1a; module top_module (input clk,input x,output z ); wire [2:0]size;dtou…

台灯学生用多少瓦的灯泡比较好?学生适用的五款护眼台灯推荐!

对于广大学生而言&#xff0c;选择一款合适的台灯灯泡瓦数至关重要。合适的瓦数不仅能够确保充足而均匀的照明&#xff0c;避免眼睛疲劳&#xff0c;还能在一定程度上节省能源。那么&#xff0c;台灯学生用多少瓦的灯泡比较好呢&#xff1f;今天就给大家科普一下&#xff0c;顺…

matlab实现遗传算法与蚁群算法

一、要求 1.利用matlab实现遗传算法和蚁群算法&#xff0c;解决相关问题 2.体会两种算法的具体作用 二、原理 &#xff08;1&#xff09;遗传算法&#xff1a; 不断循环&#xff0c;直到寻找出一个解 1. 检查每个染色体&#xff0c;看它解决问题的性能怎样&#xff0c;并…

C# for/foreach 循环

一个 for 循环是一个允许您编写一个执行特定次数的循环的重复控制结构。 语法 C# 中 for 循环的语法&#xff1a; for ( init; condition; increment ) {statement(s); } 下面是 for 循环的控制流&#xff1a; init 会首先被执行&#xff0c;且只会执行一次。这一步允许您声…

【协议-HTTPS】

https https是在http协议的基础上&#xff0c;添加了SSL/TLS握手以及数据加密传输&#xff0c;也属于应用层协议。 httpshttp加密认证完整性保护 https交互图&#xff1a; HTTPS的整体过程分为证书验证和数据传输阶段&#xff1a; ① 证书验证阶段 浏览器发起 HTTPS 请求 服务…

Verilog刷题笔记44

题目&#xff1a;Consider the n-bit shift register circuit shown below: 解题&#xff1a; module top_module (input clk,input w, R, E, L,output Q );always(posedge clk)beginif(L1)Q<R;elseQ<(E1)?w:Q;endendmodule结果正确&#xff1a; 注意点&#xff1a; …

Web实现名言生成器:JavaScript DOM基础与实例教程

&#x1f31f; 前言 欢迎来到我的技术小宇宙&#xff01;&#x1f30c; 这里不仅是我记录技术点滴的后花园&#xff0c;也是我分享学习心得和项目经验的乐园。&#x1f4da; 无论你是技术小白还是资深大牛&#xff0c;这里总有一些内容能触动你的好奇心。&#x1f50d; &#x…

iscsi网络协议(连接硬件设备)

iscsi概念 iscsi是一种互联网协议&#xff0c;用于将存储设备&#xff08;如硬盘驱动器或磁带驱动器&#xff09;通过网络连接到计算机。它是一种存储区域网络&#xff08;SAN&#xff09;技术&#xff0c;允许服务器通过网络连接到存储设备&#xff0c;就像它们是本地设备一样…

Godot 学习笔记(4):一切以场景为中心

文章目录 前言场景搭建新建子场景最简单的按钮事件 手动控制场景手动加载场景添加多个场景对象更快速的获取脚本对象 删除多个场景对象脚本命名的问题 总结 前言 Godot的场景是C#与Godot最后的中间连接。我们解决了场景的加载&#xff0c;我们基本可以保证C#和godot之间的彻底…

springcloud第4季 负载均衡的介绍3

一 loadbalance 1.1 负载均衡的介绍 使用注解loadbalance&#xff0c;是一个客户端的负载均衡器&#xff1b;通过之前已经从注册中心拉取缓存到本地的服务列表中&#xff0c;获取服务进行轮询负载请求服务列表中的数据。 轮询原理 1.2 loadbalance工作流程 loadBalance工作…