最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

springboot實(shí)現(xiàn)防重復(fù)提交和防重復(fù)點(diǎn)擊的示例

 更新時間:2020年09月29日 08:34:42   作者:DaleyZou''''s  
這篇文章主要介紹了springboot實(shí)現(xiàn)防重復(fù)提交和防重復(fù)點(diǎn)擊的示例,幫助大家更好的理解和學(xué)習(xí)springboot框架,感興趣的朋友可以了解下

背景

同一條數(shù)據(jù)被用戶點(diǎn)擊了多次,導(dǎo)致數(shù)據(jù)冗余,需要防止弱網(wǎng)絡(luò)等環(huán)境下的重復(fù)點(diǎn)擊

目標(biāo)

通過在指定的接口處添加注解,實(shí)現(xiàn)根據(jù)指定的接口參數(shù)來防重復(fù)點(diǎn)擊

說明

這里的重復(fù)點(diǎn)擊是指在指定的時間段內(nèi)多次點(diǎn)擊按鈕

技術(shù)方案

springboot + redis鎖 + 注解

使用 feign client 進(jìn)行請求測試

最終的使用實(shí)例

1、根據(jù)接口收到 PathVariable 參數(shù)判斷唯一

/**
  * 根據(jù)請求參數(shù)里的 PathVariable 里獲取的變量進(jìn)行接口級別防重復(fù)點(diǎn)擊
  *
  * @param testId 測試id
  * @param requestVo 請求參數(shù)
  * @return
  * @author daleyzou
  */
 @PostMapping("/test/{testId}")
 @NoRepeatSubmit(location = "thisIsTestLocation", seconds = 6)
 public RsVo thisIsTestLocation(@PathVariable Integer testId, @RequestBody RequestVo requestVo) throws Throwable {
  // 睡眠 5 秒,模擬業(yè)務(wù)邏輯
  Thread.sleep(5);
  return RsVo.success("test is return success");
 }

2、根據(jù)接口收到的 RequestBody 中指定變量名的值判斷唯一

/**
  * 根據(jù)請求參數(shù)里的 RequestBody 里獲取指定名稱的變量param5的值進(jìn)行接口級別防重復(fù)點(diǎn)擊
  *
  * @param testId 測試id
  * @param requestVo 請求參數(shù)
  * @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 秒,模擬業(yè)務(wù)邏輯
  Thread.sleep(5);
  return RsVo.success("test is return success");
 }

ps: jedis 2.9 和 springboot有各種兼容問題,無奈只有降低springboot的版本了

運(yùn)行結(jié)果

收到響應(yīng):{"succeeded":true,"code":500,"msg":"操作過于頻繁,請稍后重試","data":null}
收到響應(yīng):{"succeeded":true,"code":500,"msg":"操作過于頻繁,請稍后重試","data":null}
收到響應(yīng):{"succeeded":true,"code":500,"msg":"操作過于頻繁,請稍后重試","data":null}
收到響應(yīng):{"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 防重復(fù)點(diǎn)擊測試類
 * @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("收到響應(yīng):" + 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("收到響應(yīng):" + 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 重復(fù)點(diǎn)擊的切面
 * @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";
 /**
  * 要掃描的參數(shù)位置
  * */
 int argIndex() default 0;
 /**
  * 參數(shù)名稱
  * */
 String name() default "";
}

根據(jù)指定的注解定義一個切面,根據(jù)參數(shù)中的指定值來判斷請求是否重復(fù)

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;

 /**
  * 橫切點(diǎn)
  */
 @Pointcut("@annotation(noRepeatSubmit)")
 public void repeatPoint(NoRepeatSubmit noRepeatSubmit) {
 }

 /**
  * 接收請求,并記錄數(shù)據(jù)
  */
 @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("運(yùn)行業(yè)務(wù)代碼出錯", 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];
   // 設(shè)置些屬性是可以訪問的
   f.setAccessible(true);
   Object val = new Object();
   try {
    val = f.get(obj);
    // 得到此屬性的值
    // 設(shè)置鍵值
    map.put(f.getName(), val);
   } catch (IllegalArgumentException e) {
    logger.error("getKeyAndValue IllegalArgumentException", e);
   } catch (IllegalAccessException e) {
    logger.error("getKeyAndValue IllegalAccessException", e);
   }

  }
  logger.info("掃描結(jié)果:" + gson.toJson(map));
  return map;
 }
}

項(xiàng)目完整代碼

https://github.com/daleyzou/PreventRepeatSubmit

以上就是springboot實(shí)現(xiàn)防重復(fù)提交和防重復(fù)點(diǎn)擊的示例的詳細(xì)內(nèi)容,更多關(guān)于springboot實(shí)現(xiàn)防重復(fù)提交和防重復(fù)點(diǎn)擊的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • java中設(shè)計(jì)模式之適配器模式

    java中設(shè)計(jì)模式之適配器模式

    這篇文章主要介紹了java中設(shè)計(jì)模式之適配器模式的相關(guān)資料,適配器模式將一個類的接口轉(zhuǎn)換成客戶期望的另一個接口。適配器讓原本不兼容的類可以合作得親密無間,需要的朋友可以參考下
    2017-09-09
  • Java Bean與xml互相轉(zhuǎn)換的方法分析

    Java Bean與xml互相轉(zhuǎn)換的方法分析

    這篇文章主要介紹了Java Bean與xml互相轉(zhuǎn)換的方法,結(jié)合實(shí)例形式分析了java bean與xml轉(zhuǎn)換的原理與相關(guān)操作技巧,需要的朋友可以參考下
    2018-12-12
  • 構(gòu)建SpringBoot+MyBatis+Freemarker的項(xiàng)目詳解

    構(gòu)建SpringBoot+MyBatis+Freemarker的項(xiàng)目詳解

    在本篇內(nèi)容里小編給大家整理的是關(guān)于構(gòu)建SpringBoot+MyBatis+Freemarker的項(xiàng)目的具體步驟以及實(shí)例代碼,需要的朋友們參考下。
    2019-06-06
  • 使用IDEA直接連接MySQL數(shù)據(jù)庫的方法

    使用IDEA直接連接MySQL數(shù)據(jù)庫的方法

    這篇文章主要介紹了如何使用IDEA直接連接MySQL數(shù)據(jù)庫,首先需要新建一個空項(xiàng)目,第一次連接 需要先下載驅(qū)動,文中給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧
    2024-04-04
  • Java多線程編程之ThreadLocal詳解

    Java多線程編程之ThreadLocal詳解

    這篇文章主要介紹了Java多線程編程之ThreadLocal詳解,ThreadLocal是Java中的一個線程局部變量,該變量在多線程并發(fā)執(zhí)行時,為每個線程都提供了一個獨(dú)立的副本,簡單來說,ThreadLocal提供了一種在多線程環(huán)境中,使每個線程綁定自己獨(dú)立的變量的方法,需要的朋友可以參考下
    2023-09-09
  • Springboot詳細(xì)講解RocketMQ實(shí)現(xiàn)順序消息的發(fā)送與消費(fèi)流程

    Springboot詳細(xì)講解RocketMQ實(shí)現(xiàn)順序消息的發(fā)送與消費(fèi)流程

    RocketMQ作為一款純java、分布式、隊(duì)列模型的開源消息中間件,支持事務(wù)消息、順序消息、批量消息、定時消息、消息回溯等,本篇我們了解如何實(shí)現(xiàn)順序消息的發(fā)送與消費(fèi)
    2022-06-06
  • MybatisPlus之時間處理問題

    MybatisPlus之時間處理問題

    在數(shù)據(jù)庫設(shè)計(jì)時,阿里巴巴編碼規(guī)約建議使用gmt_create和gmt_modified命名時間字段,并設(shè)置為datetime類型,本文介紹了兩種自動填充時間字段的實(shí)現(xiàn)方式:SQL級別和代碼級別(使用MyBatis?Plus),SQL級別通過設(shè)置默認(rèn)值和更新值為CURRENT_TIMESTAMP
    2024-09-09
  • Java進(jìn)階學(xué)習(xí):jar打包詳解

    Java進(jìn)階學(xué)習(xí):jar打包詳解

    Java進(jìn)階學(xué)習(xí):jar打包詳解...
    2006-12-12
  • Java Date類常用示例_動力節(jié)點(diǎn)Java學(xué)院整理

    Java Date類常用示例_動力節(jié)點(diǎn)Java學(xué)院整理

    在JDK1.0中,Date類是唯一的一個代表時間的類,但是由于Date類不便于實(shí)現(xiàn)國際化,所以從JDK1.1版本開始,推薦使用Calendar類進(jìn)行時間和日期處理。這里簡單介紹一下Date類的使用,需要的朋友可以參考下
    2017-05-05
  • Java中for與foreach的區(qū)別

    Java中for與foreach的區(qū)別

    本文主要介紹了Java中for與foreach的區(qū)別,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2022-05-05

最新評論

襄垣县| 昌图县| 广德县| 盐山县| 延吉市| 仁化县| 富宁县| 南宫市| 孟村| 齐齐哈尔市| 萝北县| 启东市| 高唐县| 咸宁市| 白沙| 福贡县| 电白县| 阳朔县| 海口市| 岑巩县| 新昌县| 沽源县| 辽宁省| 平阳县| 商洛市| 壤塘县| 道孚县| 盘山县| 探索| 洛隆县| 玉环县| 济南市| 绥滨县| 卢龙县| 湟源县| 金塔县| 来宾市| 长子县| 南丰县| 漯河市| 横山县|