开源宝藏:Smart-Admin 重复提交防护的 AOP 切面实现详解

ops/2024/11/23 19:35:15/

首先,说下重复提交问题,基本上解决方案,核心都是根据URL、参数、token等,有一个唯一值检验是否重复提交。

而下面这个是根据用户id,唯一值进行判定,使用两种缓存方式,redis和caffeine,可以通过配置修改使用那种方式。

        <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</artifactId></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId><version>3.12.0</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId><version>3.0.5</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-cache</artifactId></dependency><dependency><groupId>com.github.ben-manes.caffeine</groupId><artifactId>caffeine</artifactId></dependency>
package net.lab1024.sa.common.module.support.repeatsubmit.annoation;import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;/*** 标记 需要防止重复提交 的注解<br>* 单位:毫秒** @Author 1024创新实验室: 胡克* @Date 2020-11-25 20:56:58* @Wechat zhuoda1024* @Email lab1024@163.com* @Copyright 1024创新实验室 ( https://1024lab.net )*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface RepeatSubmit {/*** 重复提交间隔时间/毫秒** @return*/int value() default 300;/*** 最长间隔30s*/int MAX_INTERVAL = 30000;
}
package net.lab1024.sa.common.module.support.repeatsubmit.ticket;import java.util.function.Function;/*** 凭证(用于校验重复提交的东西)** @Author 1024创新实验室: 罗伊* @Date 2020-11-25 20:56:58* @Wechat zhuoda1024* @Email lab1024@163.com* @Copyright 1024创新实验室 ( https://1024lab.net )*/
public abstract class AbstractRepeatSubmitTicket {private Function<String, String> ticketFunction;public AbstractRepeatSubmitTicket(Function<String, String> ticketFunction) {this.ticketFunction = ticketFunction;}/*** 获取凭证** @param ticketToken* @return*/public String getTicket(String ticketToken) {return this.ticketFunction.apply(ticketToken);}/*** 获取凭证 时间戳** @param ticket* @return*/public abstract Long getTicketTimestamp(String ticket);/*** 设置本次请求时间** @param ticket*/public abstract void putTicket(String ticket);/*** 移除凭证** @param ticket*/public abstract void removeTicket(String ticket);
}
import net.lab1024.sa.common.common.constant.StringConst;
import net.lab1024.sa.common.common.util.SmartRequestUtil;
import net.lab1024.sa.common.module.support.repeatsubmit.RepeatSubmitAspect;
import net.lab1024.sa.common.module.support.repeatsubmit.ticket.RepeatSubmitCaffeineTicket;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;/*** 重复提交配置** @Author 1024创新实验室: 罗伊* @Date 2021/10/9 18:47* @Wechat zhuoda1024* @Email lab1024@163.com* @Copyright 1024创新实验室 ( https://1024lab.net )*/
@Configuration
public class RepeatSubmitConfig {@Beanpublic RepeatSubmitAspect repeatSubmitAspect() {RepeatSubmitCaffeineTicket caffeineTicket = new RepeatSubmitCaffeineTicket(this::ticket);return new RepeatSubmitAspect(caffeineTicket);}/*** 获取指明某个用户的凭证** @return*/private String ticket(String servletPath) {Long userId = SmartRequestUtil.getRequestUserId();if (null == userId) {return StringConst.EMPTY;}return servletPath + "_" + userId;}
}
package net.lab1024.sa.common.module.support.repeatsubmit.ticket;import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import net.lab1024.sa.common.module.support.repeatsubmit.annoation.RepeatSubmit;import java.util.concurrent.TimeUnit;
import java.util.function.Function;/*** 凭证(内存实现)** @Author 1024创新实验室: 罗伊* @Date 2020-11-25 20:56:58* @Wechat zhuoda1024* @Email lab1024@163.com* @Copyright 1024创新实验室 ( https://1024lab.net )*/
public class RepeatSubmitCaffeineTicket extends AbstractRepeatSubmitTicket {/*** 限制缓存最大数量 超过后先放入的会自动移除* 默认缓存时间* 初始大小为:100万*/private static Cache<String, Long> cache = Caffeine.newBuilder().maximumSize(100 * 10000).expireAfterWrite(RepeatSubmit.MAX_INTERVAL, TimeUnit.MILLISECONDS).build();public RepeatSubmitCaffeineTicket(Function<String, String> ticketFunction) {super(ticketFunction);}@Overridepublic Long getTicketTimestamp(String ticket) {return cache.getIfPresent(ticket);}@Overridepublic void putTicket(String ticket) {cache.put(ticket, System.currentTimeMillis());}@Overridepublic void removeTicket(String ticket) {cache.invalidate(ticket);}
}
package net.lab1024.sa.common.module.support.repeatsubmit.ticket;import net.lab1024.sa.common.module.support.repeatsubmit.annoation.RepeatSubmit;
import org.springframework.data.redis.core.ValueOperations;import java.util.concurrent.TimeUnit;
import java.util.function.Function;/*** 凭证(redis实现)** @Author 1024创新实验室: 罗伊* @Date 2020-11-25 20:56:58* @Wechat zhuoda1024* @Email lab1024@163.com* @Copyright 1024创新实验室 ( https://1024lab.net )*/
public class RepeatSubmitRedisTicket extends AbstractRepeatSubmitTicket {private ValueOperations<String, String> redisValueOperations;public RepeatSubmitRedisTicket(ValueOperations<String, String> redisValueOperations,Function<String, String> ticketFunction) {super(ticketFunction);this.redisValueOperations = redisValueOperations;}@Overridepublic Long getTicketTimestamp(String ticket) {Long timeStamp = System.currentTimeMillis();boolean setFlag = redisValueOperations.setIfAbsent(ticket, String.valueOf(timeStamp), RepeatSubmit.MAX_INTERVAL, TimeUnit.MILLISECONDS);if (!setFlag) {timeStamp = Long.valueOf(redisValueOperations.get(ticket));}return timeStamp;}@Overridepublic void putTicket(String ticket) {redisValueOperations.getOperations().delete(ticket);this.getTicketTimestamp(ticket);}@Overridepublic void removeTicket(String ticket) {redisValueOperations.getOperations().delete(ticket);}
}
package net.lab1024.sa.common.module.support.repeatsubmit;import lombok.extern.slf4j.Slf4j;
import net.lab1024.sa.common.common.code.UserErrorCode;
import net.lab1024.sa.common.common.domain.ResponseDTO;
import net.lab1024.sa.common.module.support.repeatsubmit.annoation.RepeatSubmit;
import net.lab1024.sa.common.module.support.repeatsubmit.ticket.AbstractRepeatSubmitTicket;
import org.apache.commons.lang3.StringUtils;
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.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;import java.lang.reflect.Method;/*** 重复提交 aop切口** @Author 1024创新实验室: 胡克* @Date 2020-11-25 20:56:58* @Wechat zhuoda1024* @Email lab1024@163.com* @Copyright 1024创新实验室 ( https://1024lab.net )*/
@Aspect
@Slf4j
public class RepeatSubmitAspect {private AbstractRepeatSubmitTicket repeatSubmitTicket;/*** 获取凭证信息* rep** @param repeatSubmitTicket*/public RepeatSubmitAspect(AbstractRepeatSubmitTicket repeatSubmitTicket) {this.repeatSubmitTicket = repeatSubmitTicket;}/*** 定义切入点** @param point* @return* @throws Throwable*/@Around("@annotation(net.lab1024.sa.common.module.support.repeatsubmit.annoation.RepeatSubmit)")public Object around(ProceedingJoinPoint point) throws Throwable {ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();String ticketToken = attributes.getRequest().getServletPath();String ticket = this.repeatSubmitTicket.getTicket(ticketToken);if (StringUtils.isEmpty(ticket)) {return point.proceed();}Long timeStamp = this.repeatSubmitTicket.getTicketTimestamp(ticket);if (timeStamp != null) {Method method = ((MethodSignature) point.getSignature()).getMethod();RepeatSubmit annotation = method.getAnnotation(RepeatSubmit.class);// 说明注解去掉了if (annotation != null) {return point.proceed();}int interval = Math.min(annotation.value(), RepeatSubmit.MAX_INTERVAL);if (System.currentTimeMillis() < timeStamp + interval) {// 提交频繁return ResponseDTO.error(UserErrorCode.REPEAT_SUBMIT);}}Object obj = null;try {// 先给 ticket 设置在执行中this.repeatSubmitTicket.putTicket(ticket);obj = point.proceed();} catch (Throwable throwable) {log.error("", throwable);throw throwable;} finally {this.repeatSubmitTicket.removeTicket(ticket);}return obj;}}

参考链接:https://github.com/1024-lab/smart-admin


http://www.ppmy.cn/ops/136120.html

相关文章

工厂方法模式

工厂方法模式详解 定义 工厂方法模式&#xff08;Factory Method Pattern&#xff09;是一种创建型设计模式&#xff0c;定义一个创建对象的接口&#xff0c;但让子类决定要实例化的具体类。通过这种方式&#xff0c;工厂方法模式将对象的实例化推迟到子类。 特点 解耦性&a…

鸿蒙安全控件之粘贴控件简介

粘贴控件是一种特殊的系统安全控件&#xff0c;它允许应用在用户的授权下无提示地读取剪贴板数据。 在应用集成粘贴控件后&#xff0c;用户点击该控件&#xff0c;应用读取剪贴板数据时不会弹窗提示。可以用于任何应用需要读取剪贴板的场景&#xff0c;避免弹窗提示对用户造成…

通过奖励引导树搜索增强大模型(LLM)的推理能力,原理介绍与代码实现

大家好&#xff0c;我是微学AI&#xff0c;今天给大家介绍一下通过奖励引导树搜索增强大模型LLM的推理能力&#xff0c;原理介绍与代码实现。本文主要探讨了如何通过奖励引导树搜索来增强大型语言模型&#xff08;LLM&#xff09;的推理能力。首先&#xff0c;文章详细介绍了奖…

【人工智能】Python与Scikit-learn的模型选择与调参:用GridSearchCV和RandomizedSearchCV提升模型性能

解锁Python编程的无限可能:《奇妙的Python》带你漫游代码世界 在机器学习建模过程中,模型的表现往往取决于参数的选择与优化。Scikit-learn提供了便捷的工具GridSearchCV和RandomizedSearchCV,帮助我们在参数空间中搜索最佳组合以提升模型表现。本文将从理论和实践两个角度…

新160个crackme - 100-E-crackme

运行分析 需根据机器码&#xff0c;填写正确注册码 PE分析 C程序&#xff0c;32位&#xff0c;无壳 静态分析&动态调试 ida无法搜到字符串&#xff0c;使用暂停法找关键函数 首先启动ida动态调试&#xff0c;点击注册来到错误弹窗 点击Debugger -> Pause process 发现断…

【AI系统】GPU 架构与 CUDA 关系

GPU 架构与 CUDA 关系 本文会讲解英伟达 GPU 硬件的基础概念&#xff0c;其次会讲解 CUDA&#xff08;Compute Unified Device Architecture&#xff09;并行计算平台和编程模型&#xff0c;详细讲解 CUDA 线程层次结构&#xff0c;最后将讲解 GPU 的算力是如何计算的&#xf…

成功案例 | Fortinet助力宾堡打造数字化安全“美味王国”

在全球数字化转型的大背景下&#xff0c;烘焙食品行业也迎来了前所未有的变革。2024年全球烘焙食品市场规模预计将达到2337.7亿美元1&#xff0c;而数字化转型则成为推动这一市场增长的关键因素之一。 作为全球首屈一指的烘焙食品生产企业&#xff0c;宾堡集团&#xff08;Gru…

Ubuntu22.04安装CH343驱动并创建udev规则

驱动说明 Linux系统提供CH34*系列 USB UART 设备配合使用的默认 CDC-ACM 驱动程序。驱动程序文件名为CDC-ACM。CDC-ACM 驱动程序控制特定设备的能力有限。此通用驱动程序不了解特定设备协议。因此&#xff0c;设备制造商可以创建能够访问设备特定功能集&#xff08;例如硬件流…