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

devtools/2024/11/24 7:35:29/

首先,说下重复提交问题,基本上解决方案,核心都是根据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/devtools/136492.html

相关文章

2024亚太杯C题宠物行业及相关产业的发展分析和策略——成品参考思路模型代码

更多资源请关注下方名片获取 1 总体分析 1.1 问题背景&#xff1a; 随着人们消费理念的发展&#xff0c;宠物行业这一新兴产业在全球范围内逐渐兴起&#xff0c;得益于经济的快速发展和人均收入的提升。1992年&#xff0c;中国小动物保护协会成立&#xff0c;随后国际宠物品…

【Ubuntu】如何在Ubuntu系统中查看端口是否可用

文章目录 前言一、使用netstat命令二、使用ss命令三、使用lsof命令四、使用nc&#xff08;netcat&#xff09;命令总结 前言 本文介绍了如何在Ubuntu系统中查看端口是否可用的方法&#xff0c;并给出了具体的命令示例&#xff0c;帮助用户通过命令行工具检测端口的开放状态。 …

论文阅读:SIMBA: single-cell embedding along with features

Chen, H., Ryu, J., Vinyard, M.E. et al. SIMBA: single-cell embedding along with features. Nat Methods 21, 1003–1013 (2024). 论文地址&#xff1a;https://doi.org/10.1038/s41592-023-01899-8 代码地址&#xff1a;https://github.com/pinellolab/simba. 摘要 大多…

⭐️ GitHub Star 数量前十的工作流项目

文章开始前&#xff0c;我们先做个小调查&#xff1a;在日常工作中&#xff0c;你会使用自动化工作流工具吗&#xff1f;&#x1f64b; 事实上&#xff0c;工作流工具已经变成了提升效率的关键。其实在此之前我们已经写过一篇博客&#xff0c;跟大家分享五个好用的工作流工具。…

SpringBoot整合SpringSecurity实现一个简单的认证与授权应用

1、SpringSecurity 的简介 Spring Security 是一个功能强大且高度可定制的身份验证和访问控制框架&#xff0c;它是 Spring 项目组中用来提供安全认证服务的框架&#xff0c;能够为基于 Sprin g的企业应用系统提供声明式的安全访问控制解决方案。 Spring Security 的前身是 A…

机器学习实战:银行客户是否认购定期存款

项目结构与步骤 1. 项目概述 项目名称&#xff1a;葡萄牙银行电话营销活动分析与定期存款认购预测目标&#xff1a;通过分析银行的电话营销数据&#xff0c;构建模型预测客户是否会认购定期存款。数据来源&#xff1a;葡萄牙银行营销活动数据集关键挑战&#xff1a;数据不平衡…

YOLOv8-ultralytics-8.2.103部分代码阅读笔记-utils.py

utils.py ultralytics\nn\modules\utils.py 目录 utils.py 1.所需的库和模块 2.def _get_clones(module, n): 3.def bias_init_with_prob(prior_prob0.01): 4.def linear_init(module): 5.def inverse_sigmoid(x, eps1e-5): 6.def multi_scale_deformable_attn_py…

vscode下面python调试报错ImportError: cannot import name ‘Literal‘ from ‘typing‘

1 问题描述 我在vscode下面编写python程序&#xff0c;这个程序是在一个英伟达anoconda环境下的项目。之前能运行能调试&#xff0c;最近发现只能运行ctlf5&#xff0c;但是使用f5进行调试时&#xff0c;报错“File “c:\Users\86137.vscode\extensions\ms-python.debugpy-202…