当前位置: 首页 > ds >正文

一种基于注解与AOP的Spring Boot接口限流防刷方案

1. 添加Maven依赖

<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency>
</dependencies>

2. 创建自定义注解

import java.lang.annotation.*;/*** 接口防刷注解*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface AccessLimit {/*** 限制时间范围(秒)*/int time() default 60;/*** 时间范围内最大访问次数*/int maxCount() default 10;/*** 是否检查IP地址*/boolean checkIp() default true;/*** 是否检查用户身份(需要登录)*/boolean checkUser() default false;/*** 触发限制时的提示信息*/String message() default "操作过于频繁,请稍后再试";
}

3. 创建AOP切面实现防护逻辑

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;@Aspect
@Component
public class AccessLimitAspect {@Autowiredprivate RedisTemplate<String, Object> redisTemplate;@Around("@annotation(accessLimit)")public Object around(ProceedingJoinPoint joinPoint, AccessLimit accessLimit) throws Throwable {// 获取请求对象ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();if (attributes == null) {return joinPoint.proceed();}HttpServletRequest request = attributes.getRequest();MethodSignature signature = (MethodSignature) joinPoint.getSignature();Method method = signature.getMethod();// 构建Redis keyString key = buildKey(request, method, accessLimit);// 获取当前计数ValueOperations<String, Object> operations = redisTemplate.opsForValue();Integer count = (Integer) operations.get(key);if (count == null) {// 第一次访问operations.set(key, 1, accessLimit.time(), TimeUnit.SECONDS);} else if (count < accessLimit.maxCount()) {// 计数增加operations.increment(key);} else {// 超出限制,抛出异常throw new RuntimeException(accessLimit.message());}return joinPoint.proceed();}/*** 构建Redis key*/private String buildKey(HttpServletRequest request, Method method, AccessLimit accessLimit) {StringBuilder key = new StringBuilder("access_limit:");// 添加方法标识key.append(method.getDeclaringClass().getName()).append(".").append(method.getName()).append(":");// 添加IP标识if (accessLimit.checkIp()) {String ip = getClientIp(request);key.append(ip).append(":");}// 添加用户标识(需要实现获取当前用户的方法)if (accessLimit.checkUser()) {// 这里需要根据你的用户系统实现获取当前用户ID的方法String userId = getCurrentUserId();if (userId != null) {key.append(userId).append(":");}}return key.toString();}/*** 获取客户端IP*/private String getClientIp(HttpServletRequest request) {String ip = request.getHeader("X-Forwarded-For");if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {// 多次反向代理后会有多个ip值,第一个ip才是真实ipif (ip.contains(",")) {ip = ip.split(",")[0];}}if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {ip = request.getHeader("Proxy-Client-IP");}if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {ip = request.getHeader("WL-Proxy-Client-IP");}if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {ip = request.getHeader("HTTP_CLIENT_IP");}if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {ip = request.getHeader("HTTP_X_FORWARDED_FOR");}if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {ip = request.getRemoteAddr();}return ip;}/*** 获取当前用户ID(需要根据实际情况实现)*/private String getCurrentUserId() {// 实现获取当前用户ID的逻辑// 可以从Session、Token或Spring Security上下文等获取return null;}
}

4. 创建全局异常处理器

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;@RestControllerAdvice
public class GlobalExceptionHandler {@ExceptionHandler(RuntimeException.class)public Result handleRuntimeException(RuntimeException e) {return Result.error(e.getMessage());}
}

5. 在Controller中使用注解

import org.springframework.web.bind.annotation.*;@RestController
@RequestMapping("/api")
public class DemoController {// 基于IP的限制:60秒内最多访问10次@AccessLimit(time = 60, maxCount = 10, checkIp = true, checkUser = false)@GetMapping("/public/data")public String getPublicData() {return "这是公开数据";}// 基于用户的限制:30秒内最多访问5次@AccessLimit(time = 30, maxCount = 5, checkIp = false, checkUser = true)@GetMapping("/user/data")public String getUserData() {return "这是用户数据";}// 同时基于IP和用户的限制:60秒内最多访问3次@AccessLimit(time = 60, maxCount = 3, checkIp = true, checkUser = true)@PostMapping("/submit")public String submitData(@RequestBody String data) {return "提交成功: " + data;}
}
http://www.xdnf.cn/news/20244.html

相关文章:

  • C#海康车牌识别实战指南带源码
  • VAE(变分自动编码器)技术解析
  • iOS混淆工具实战 在线教育直播类 App 的课程与互动安全防护
  • FairGuard游戏加固产品常见问题解答
  • 云市场周报 (2025.09.05):解读腾讯云AI安全、阿里数据湖与KubeVela
  • C语言中常见的数据结构及其代码实现
  • 数据传输优化-异步不阻塞处理增强首屏体验
  • 自演化大语言模型的技术背景
  • 心理学家称AI大模型交流正在引发前所未见的精神障碍
  • 手把手教你用CUDA Graph:将你的LLM推理延迟降低一个数量级
  • 51单片机------中断系统
  • 51单片机基础day3
  • 开源混合专家大语言模型(DBRX)
  • Spring WebFlux 流式数据拉取与推送的实现
  • UIViewController生命周期
  • Word封面对齐技巧(自制)
  • UE4 UAT 的六大流程 build cook stage pacakge archive deploy 与UAT的参数
  • 硬件(二) 中断、定时器、PWM
  • 当电力设计遇上AI:良策金宝AI如何重构行业效率边界?
  • Linux2.6内核进程O(1)调度队列
  • 电机控制(三)-电机控制方法基础
  • Java集合---Collection接口和Map接口
  • C++:类和对象(中)
  • 在线测评系统---第n天
  • 执行select * from a where rownum<1;,数据库子进程崩溃,业务中断。
  • LabVIEW--二维数组、三维数组、四维数组
  • Pydantic模型验证测试:你的API数据真的安全吗?
  • Selenium 页面加载超时pageLoadTimeout与 iframe加载关系解析
  • 静态电流Iq 和 ICONT_MAX
  • GD32入门到实战32--产品配置参数存储方案 (NORFLASH)