背景

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

目标

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

说明

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

技术方案

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. 学习seo赚钱一定要有超前的思路和眼光

    http://www.wocaoseo.com/thread-100-1-1.html        日子过的真是快,一天又一天,一年又一年,虽然过年的脚步将近,火车票的问题还是没有解决,昨天忙活了半 ...

  2. 基于.NetCore3.1系列 —— 日志记录之初识Serilog

    一.前言 对内置日志系统的整体实现进行了介绍之后,可以通过使用内置记录器来实现日志的输出路径.而在实际项目开发中,使用第三方日志框架(如: Log4Net.NLog.Loggr.Serilog.Sen ...

  3. python练习 - 文本的平均列数+CSV格式清洗与转换

    文本的平均列数 描述 打印输出附件文件的平均列数,计算方法如下:‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‮‬‪‬‪‬ ...

  4. gdb我在我本机上p不了,在别人机子上可以

    gdb我在我本机上p不了,在别人机子上可以,不知道什么 (gdb) p EventFlow->devicetypeThere is no member or method named devic ...

  5. 利用OpenCV进行H264视频编码的简易方式

    在Python下,利用pip安装预编译的opencv库,并实现h264格式的视频编码. 1. 安装OpenCV $ pip install opencv-python 建议在python虚拟环境下安装 ...

  6. Kubernetes-14:一文详解Pod、Node调度规则(亲和性、污点、容忍、固定节点)

    Kubernetes Pod调度说明 简介 Scheduler 是 Kubernetes 的调度器,主要任务是把定义的Pod分配到集群的节点上,听起来非常简单,但要考虑需要方面的问题: 公平:如何保证 ...

  7. Unity可编程管线的顶点光照Shader

    UnityCG.cginc有一个叫ShadeVertexLightsFull的函数可以用来计算顶点光照. 源码如下: // Used in Vertex pass: Calculates diffus ...

  8. C#转PHP

    官方主页 https://github.com/isukces/cs2php 快速开始 http://www.cs2php.com/how-to-begin.htm#.W2rBhC2B3mI 如何在V ...

  9. POJ - 3037-Skiing(邻接表+Dijkstra)

    Bessie and the rest of Farmer John's cows are taking a trip this winter to go skiing. One day Bessie ...

  10. latex pdf 转 eps

    latex pdf 转 eps 方法一,使用命令行,缺点是得到的文件有点大 pdf 转 ps, pdf2ps input.pdf output.ps ps 转 eps, ps2eps input.ps ...