背景

同一条数据被用户点击了多次,导致数据冗余,需要防止弱网络等环境下的重复点击

目标

通过在指定的接口处添加注解,实现根据指定的接口参数来防重复点击

说明

这里的重复点击是指在指定的时间段内多次点击按钮

技术方案

springboot + redis锁 + 注解

使用 feign client 进行请求测试

最终的使用实例

1、根据接口收到 PathVariable 参数判断唯一

/**
* 根据请求参数里的 PathVariable 里获取的变量进行接口级别防重复点击
*
* @param testId 测试id
* @param requestVo 请求参数
* @return
* @author daleyzou
*/
@PostMapping("/test/{testId}")
@NoRepeatSubmit(location = "thisIsTestLocation", seconds = 6)
public RsVo thisIsTestLocation(@PathVariable Integer testId, @RequestBody RequestVo requestVo) throws Throwable {
// 睡眠 5 秒,模拟业务逻辑
Thread.sleep(5);
return RsVo.success("test is return success");
}

2、根据接口收到的 RequestBody 中指定变量名的值判断唯一

/**
* 根据请求参数里的 RequestBody 里获取指定名称的变量param5的值进行接口级别防重复点击
*
* @param testId 测试id
* @param requestVo 请求参数
* @return
* @author daleyzou
*/
@PostMapping("/test/{testId}")
@NoRepeatSubmit(location = "thisIsTestBody", seconds = 6, argIndex = 1, name = "param5")
public RsVo thisIsTestBody(@PathVariable Integer testId, @RequestBody RequestVo requestVo) throws Throwable {
// 睡眠 5 秒,模拟业务逻辑
Thread.sleep(5);
return RsVo.success("test is return success");
}

ps: jedis 2.9 和 springboot有各种兼容问题,无奈只有降低springboot的版本了

运行结果

收到响应:{"succeeded":true,"code":500,"msg":"操作过于频繁,请稍后重试","data":null}
收到响应:{"succeeded":true,"code":500,"msg":"操作过于频繁,请稍后重试","data":null}
收到响应:{"succeeded":true,"code":500,"msg":"操作过于频繁,请稍后重试","data":null}
收到响应:{"succeeded":true,"code":200,"msg":"success","data":"test is return success"}

测试用例

package com.dalelyzou.preventrepeatsubmit.controller;

import com.dalelyzou.preventrepeatsubmit.PreventrepeatsubmitApplicationTests;
import com.dalelyzou.preventrepeatsubmit.service.AsyncFeginService;
import com.dalelyzou.preventrepeatsubmit.vo.RequestVo;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired; import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; /**
* TestControllerTest
* @description 防重复点击测试类
* @author daleyzou
* @date 2020年09月28日 17:13
* @version 1.3.1
*/
class TestControllerTest extends PreventrepeatsubmitApplicationTests {
@Autowired
AsyncFeginService asyncFeginService; @Test
public void thisIsTestLocation() throws IOException {
RequestVo requestVo = new RequestVo();
requestVo.setParam5("random");
ExecutorService executorService = Executors.newFixedThreadPool(4);
for (int i = 0; i <= 3; i++) {
executorService.execute(() -> {
String kl = asyncFeginService.thisIsTestLocation(requestVo);
System.err.println("收到响应:" + kl);
});
}
System.in.read();
} @Test
public void thisIsTestBody() throws IOException {
RequestVo requestVo = new RequestVo();
requestVo.setParam5("special");
ExecutorService executorService = Executors.newFixedThreadPool(4);
for (int i = 0; i <= 3; i++) {
executorService.execute(() -> {
String kl = asyncFeginService.thisIsTestBody(requestVo);
System.err.println("收到响应:" + kl);
});
}
System.in.read();
}
}

定义一个注解

package com.dalelyzou.preventrepeatsubmit.aspect;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; /**
* NoRepeatSubmit
* @description 重复点击的切面
* @author daleyzou
* @date 2020年09月23日 14:35
* @version 1.4.8
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface NoRepeatSubmit {
/**
* 锁过期的时间
* */
int seconds() default 5;
/**
* 锁的位置
* */
String location() default "NoRepeatSubmit";
/**
* 要扫描的参数位置
* */
int argIndex() default 0;
/**
* 参数名称
* */
String name() default "";
}

根据指定的注解定义一个切面,根据参数中的指定值来判断请求是否重复

package com.dalelyzou.preventrepeatsubmit.aspect;

import com.dalelyzou.preventrepeatsubmit.constant.RedisKey;
import com.dalelyzou.preventrepeatsubmit.service.LockService;
import com.dalelyzou.preventrepeatsubmit.vo.RsVo;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils; import java.lang.reflect.Field;
import java.util.Map; @Aspect
@Component
public class NoRepeatSubmitAspect {
private static final Logger logger = LoggerFactory.getLogger(NoRepeatSubmitAspect.class); private static Gson gson = new Gson(); private static final String SUFFIX = "SUFFIX"; @Autowired
LockService lockService; /**
* 横切点
*/
@Pointcut("@annotation(noRepeatSubmit)")
public void repeatPoint(NoRepeatSubmit noRepeatSubmit) {
} /**
* 接收请求,并记录数据
*/
@Around(value = "repeatPoint(noRepeatSubmit)")
public Object doBefore(ProceedingJoinPoint joinPoint, NoRepeatSubmit noRepeatSubmit) {
String key = RedisKey.NO_REPEAT_LOCK_PREFIX + noRepeatSubmit.location();
Object[] args = joinPoint.getArgs();
String name = noRepeatSubmit.name();
int argIndex = noRepeatSubmit.argIndex();
String suffix;
if (StringUtils.isEmpty(name)) {
suffix = String.valueOf(args[argIndex]);
} else {
Map<String, Object> keyAndValue = getKeyAndValue(args[argIndex]);
Object valueObj = keyAndValue.get(name);
if (valueObj == null) {
suffix = SUFFIX;
} else {
suffix = String.valueOf(valueObj);
}
}
key = key + ":" + suffix;
logger.info("==================================================");
for (Object arg : args) {
logger.info(gson.toJson(arg));
}
logger.info("==================================================");
int seconds = noRepeatSubmit.seconds();
logger.info("lock key : " + key);
if (!lockService.isLock(key, seconds)) {
return RsVo.fail("操作过于频繁,请稍后重试");
}
try {
Object proceed = joinPoint.proceed();
return proceed;
} catch (Throwable throwable) {
logger.error("运行业务代码出错", throwable);
throw new RuntimeException(throwable.getMessage());
} finally {
lockService.unLock(key);
}
} public static Map<String, Object> getKeyAndValue(Object obj) {
Map<String, Object> map = Maps.newHashMap();
// 得到类对象
Class userCla = (Class) obj.getClass();
/* 得到类中的所有属性集合 */
Field[] fs = userCla.getDeclaredFields();
for (int i = 0; i < fs.length; i++) {
Field f = fs[i];
// 设置些属性是可以访问的
f.setAccessible(true);
Object val = new Object();
try {
val = f.get(obj);
// 得到此属性的值
// 设置键值
map.put(f.getName(), val);
} catch (IllegalArgumentException e) {
logger.error("getKeyAndValue IllegalArgumentException", e);
} catch (IllegalAccessException e) {
logger.error("getKeyAndValue IllegalAccessException", e);
} }
logger.info("扫描结果:" + gson.toJson(map));
return map;
}
}

项目完整代码

https://github.com/daleyzou/PreventRepeatSubmit

springboot实现防重复提交和防重复点击的更多相关文章

  1. asp.net网页防刷新重复提交、防后退解决办法!

    原文发布时间为:2008-10-14 -- 来源于本人的百度文章 [由搬家工具导入] 1、提交后 禁用提交按钮(像CSDN这样)2、数据处理成功马上跳转到另外一个页面! 操作后刷新的确是个问题,你可以 ...

  2. javaEE开发中使用session同步和token机制来防止并发重复提交

    javaEE开发中使用session同步和token机制来防止并发重复提交 通常在普通的操作当中,我们不需要处理重复提交的,而且有很多方法来防止重复提交.比如在登陆过程中,通过使用redirect,可 ...

  3. Spring Boot (一) 校验表单重复提交

    一.前言 在某些情况下,由于网速慢,用户操作有误(连续点击两下提交按钮),页面卡顿等原因,可能会出现表单数据重复提交造成数据库保存多条重复数据. 存在如上问题可以交给前端解决,判断多长时间内不能再次点 ...

  4. ASP.NET Web Form和MVC中防止F5刷新引起的重复提交问题

    转载 http://www.cnblogs.com/hiteddy/archive/2012/03/29/Prevent_Resubmit_When_Refresh_Reload_In_ASP_NET ...

  5. .net防止刷新重复提交(转)

    net 防止重复提交 微软防止重复提交方案,修改版 Code ; i < cookie.Values.Count; i++)                     log.Info(" ...

  6. java web解决表单重复提交问题

    我们大家再进行web开发的时候,必不可少会遇见表单重复提交问题.今天就来给总结如何解决表单提交问题,欢迎大家交流指正. 首先我们在讨论如何解决表单重复提交问题之前先来解决三个问题:1.什么叫表单重复提 ...

  7. Struts(二十七):使用token或tokenSession防止表单重复提交

    什么是表单重复提交 表单重复提交包括以下几种情况: 前提:不刷新表单页面 1.多次点击“提交”按钮后,重复提交了多次: 2.已经提交成功之后,按“回退”按钮之后,在点击“提交”按钮后,提交成功: 3. ...

  8. easyUI的form表单重复提交处理

    1. 问题 生产环境出现过新增用户提交, 入库两条重复数据的情况; 但是我查看代码, 页面做了校验, 后台插入数据也做了校验;  出现这种几率的事件的非常小的, 但是还是会碰到, 客户会对我们的产品产 ...

  9. Restful api 防止重复提交

    当前很多网站是前后分离的,前端(android,iso,h5)通过restful API 调用 后端服务器,这就存在一个问题,对于创建操作,比如购买某个商品,如果由于某种原因,手抖,控件bug,网络错 ...

随机推荐

  1. muduo源码解析4-exception类

    exception class exception:public std::exception { }; 作用: 实现了一个异常类,继承于std::exception,主要用于实现打印线程调用栈信息. ...

  2. elementUI的隐藏组件el-scroll--滚动条

    由于原生的滚动条存在兼容性问题并且样式不是太美观,在项目中经常使用的是elementui,发现elementui中有个隐藏的组件,就是element官网使用的滚动条,可以优化滚动条样式.鼠标经过的时候 ...

  3. 分享几个好用的ui框架,以便开发

    1:Layui--经典模块化前端框架 地址:https://www.layui.com/ 2:iview--基于 Vue.js 的高质量 UI 组件库 地址:http://v1.iviewui.com ...

  4. 【Android】Android开发启动app弹出一张广告图片,Dialog可以查看大图,查看某个图片功能

    作者:程序员小冰,GitHub主页:https://github.com/QQ986945193 新浪微博:http://weibo.com/mcxiaobing 首先给大家看一下我们今天这个最终实现 ...

  5. 备份etc下的内容

    echo "start backup..."sleep 3cp -av /etc/ /data/etc`date +%F`/echo "end backup"~ ...

  6. C#委托链

    使用Delegate.Combine时,注意两点: 1. 不可以将不同签名的两个委托相互Combine. 2.如果将有返回值的两个委托A 和 B Combine,那么返回值是最后一个委托的的返回值,也 ...

  7. MySQL 数据库 查 续

    MySQL 增删查改 必知必会 4.1.13 使用 like 关键字进行模糊查询 -- 说明:模糊查询,使用查询关键字like,like意思是类似于,像...的意思 -- 模糊查询,支持两种字符匹配符 ...

  8. 机器学习,详解SVM软间隔与对偶问题

    今天是机器学习专题的第34篇文章,我们继续来聊聊SVM模型. 我们在上一篇文章当中推导了SVM模型在硬间隔的原理以及公式,最后我们消去了所有的变量,只剩下了\(\alpha\).在硬间隔模型当中,样本 ...

  9. 项目实战 - 原理讲解<-> Keras框架搭建Mtcnn人脸检测平台

    Mtcnn它是2016年中国科学院深圳研究院提出的用于人脸检测任务的多任务神经网络模型,该模型主要采用了三个级联的网络,采用候选框加分类器的思想,进行快速高效的人脸检测.这三个级联的网络分别是快速生成 ...

  10. EasyPoi导出Excel

    这几天一直在忙工作中的事情,在工作中有一个问题,可能是因为刚开始接触这个EasyPoi,对其也没有太多的理解,在项目中就使用了,有一个需求,是要导出项目中所有的表格,今天就对这个需求进行分析和实现吧; ...