<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          JAVA注解實(shí)現(xiàn)接口防刷

          共 10956字,需瀏覽 22分鐘

           ·

          2022-09-17 22:00

          點(diǎn)擊關(guān)注公眾號(hào):互聯(lián)網(wǎng)架構(gòu)師,后臺(tái)回復(fù) 2T獲取2TB學(xué)習(xí)資源!

          上一篇:Alibaba開(kāi)源內(nèi)網(wǎng)高并發(fā)編程手冊(cè).pdf

          /**
               * 測(cè)試防刷
               *
               * @param request
               * @return
               */

              @ResponseBody
              @GetMapping(value = "/testPrevent")
              @Prevent //加上該注解即可實(shí)現(xiàn)短信防刷(默認(rèn)一分鐘內(nèi)不允許重復(fù)調(diào)用,支持?jǐn)U展、配置)
              public Response testPrevent(TestRequest request) {
                  return Response.success("調(diào)用成功");
              }

          1、實(shí)現(xiàn)防刷切面PreventAop.java

          大致邏輯為:定義一切面,通過(guò)@Prevent注解作為切入點(diǎn)、在該切面的前置通知獲取該方法的所有入?yún)⒉⑵銪ase64編碼,將入?yún)ase64編碼+完整方法名作為redis的key,入?yún)⒆鳛閞eids的value,@Prevent的value作為redis的expire,存入redis;每次進(jìn)來(lái)這個(gè)切面根據(jù)入?yún)ase64編碼+完整方法名判斷redis值是否存在,存在則攔截防刷,不存在則允許調(diào)用;
          1.1 定義注解Prevent
          package com.zetting.aop;

          import java.lang.annotation.*;

          /**
           * 接口防刷注解
           * 使用:
           * 在相應(yīng)需要防刷的方法上加上
           * 該注解,即可
           *
           * @author: zetting
           * @date:2018/12/29
           */

          @Documented
          @Target({ElementType.METHOD})
          @Retention(RetentionPolicy.RUNTIME)
          public @interface Prevent {

              /**
               * 限制的時(shí)間值(秒)
               *
               * @return
               */

              String value() default "60";

              /**
               * 提示
               */

              String message() default "";

              /**
               * 策略
               *
               * @return
               */

              PreventStrategy strategy() default PreventStrategy.DEFAULT;
          }
          1.2 實(shí)現(xiàn)防刷切面PreventAop
          package com.zetting.aop;

          import com.alibaba.fastjson.JSON;
          import com.zetting.common.BusinessException;
          import com.zetting.util.RedisUtil;
          import org.aspectj.lang.JoinPoint;
          import org.aspectj.lang.annotation.Aspect;
          import org.aspectj.lang.annotation.Before;
          import org.aspectj.lang.annotation.Pointcut;
          import org.aspectj.lang.reflect.MethodSignature;
          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.Method;
          import java.util.Base64;

          /**
           * 防刷切面實(shí)現(xiàn)類(lèi)
           *
           * @author: zetting
           * @date: 2018/12/29 20:27
           */

          @Aspect
          @Component
          public class PreventAop {
              private static Logger log = LoggerFactory.getLogger(PreventAop.class);

              @Autowired
              private RedisUtil redisUtil;

              /**
               * 切入點(diǎn)
               */

              @Pointcut("@annotation(com.zetting.aop.Prevent)")
              public void pointcut() {
              }

              /**
               * 處理前
               *
               * @return
               */

              @Before("pointcut()")
              public void joinPoint(JoinPoint joinPoint) throws Exception {
                  String requestStr = JSON.toJSONString(joinPoint.getArgs()[0]);
                  if (StringUtils.isEmpty(requestStr) || requestStr.equalsIgnoreCase("{}")) {
                      throw new BusinessException("[防刷]入?yún)⒉辉试S為空");
                  }

                  MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
                  Method method = joinPoint.getTarget().getClass().getMethod(methodSignature.getName(),
                          methodSignature.getParameterTypes());

                  Prevent preventAnnotation = method.getAnnotation(Prevent.class);
                  String methodFullName = method.getDeclaringClass().getName() + method.getName();

                  entrance(preventAnnotation, requestStr,methodFullName);
                  return;
              }

              /**
               * 入口
               *
               * @param prevent
               * @param requestStr
               */

              private void entrance(Prevent prevent, String requestStr,String methodFullName) throws Exception {
                  PreventStrategy strategy = prevent.strategy();
                  switch (strategy) {
                      case DEFAULT:
                          defaultHandle(requestStr, prevent,methodFullName);
                          break;
                      default:
                          throw new BusinessException("無(wú)效的策略");
                  }
              }

              /**
               * 默認(rèn)處理方式
               *
               * @param requestStr
               * @param prevent
               */

              private void defaultHandle(String requestStr, Prevent prevent,String methodFullName) throws Exception {
                  String base64Str = toBase64String(requestStr);
                  long expire = Long.parseLong(prevent.value());

                  String resp = redisUtil.get(methodFullName+base64Str);
                  if (StringUtils.isEmpty(resp)) {
                      redisUtil.set(methodFullName+base64Str, requestStr, expire);
                  } else {
                      String message = !StringUtils.isEmpty(prevent.message()) ? prevent.message() :
                              expire + "秒內(nèi)不允許重復(fù)請(qǐng)求";
                      throw new BusinessException(message);
                  }
              }

              /**
               * 對(duì)象轉(zhuǎn)換為base64字符串
               *
               * @param obj 對(duì)象值
               * @return base64字符串
               */

              private String toBase64String(String obj) throws Exception {
                  if (StringUtils.isEmpty(obj)) {
                      return null;
                  }
                  Base64.Encoder encoder = Base64.getEncoder();
                  byte[] bytes = obj.getBytes("UTF-8");
                  return encoder.encodeToString(bytes);
              }
          }

          注:以上只展示核心代碼、其他次要代碼(例如redis配置、redis工具類(lèi)等)可下載源碼查閱

          2、使用防刷切面

          在MyController 使用防刷

          package com.zetting.modules.controller;

          import com.zetting.aop.Prevent;
          import com.zetting.common.Response;
          import com.zetting.modules.dto.TestRequest;
          import org.springframework.web.bind.annotation.GetMapping;
          import org.springframework.web.bind.annotation.ResponseBody;
          import org.springframework.web.bind.annotation.RestController;

          /**
           * 切面實(shí)現(xiàn)入?yún)⑿r?yàn)
           */

          @RestController
          public class MyController {

              /**
               * 測(cè)試防刷
               *
               * @param request
               * @return
               */

              @ResponseBody
              @GetMapping(value = "/testPrevent")
              @Prevent
              public Response testPrevent(TestRequest request) {
                  return Response.success("調(diào)用成功");
              }

              /**
               * 測(cè)試防刷
               *
               * @param request
               * @return
               */

              @ResponseBody
              @GetMapping(value = "/testPreventIncludeMessage")
              @Prevent(message = "10秒內(nèi)不允許重復(fù)調(diào)多次", value = "10")//value 表示10表示10
              public Response testPreventIncludeMessage(TestRequest request) {
                  return Response.success("調(diào)用成功");
              }
          }


          3、演示

          gitee 源碼:https://gitee.com/Zetting/my-gather/tree/master/springboot-aop-prevent

          作者:zetting
          鏈接:https://www.jianshu.com/p/697f1c5eaa3f

          -End-
          最后,關(guān)注公眾號(hào)互聯(lián)網(wǎng)架構(gòu)師,在后臺(tái)回復(fù):2T,可以獲取我整理的 Java 系列面試題和答案,非常齊全


          正文結(jié)束


          推薦閱讀 ↓↓↓

          1.求求你別在用SpringMVC了,太Low了!Spring又官宣了一個(gè)更牛逼的替代框架!

          2.從零開(kāi)始搭建創(chuàng)業(yè)公司后臺(tái)技術(shù)棧

          3.程序員一般可以從什么平臺(tái)接私活?

          4.Spring Boot+Redis+攔截器+自定義Annotation實(shí)現(xiàn)接口自動(dòng)冪等

          5.為什么國(guó)內(nèi) 996 干不過(guò)國(guó)外的 955呢?

          6.中國(guó)的鐵路訂票系統(tǒng)在世界上屬于什么水平?                        

          7.15張圖看懂瞎忙和高效的區(qū)別!

          瀏覽 61
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          評(píng)論
          圖片
          表情
          推薦
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  91AV视频播放 | 国产免费高清视频 | 美女肏逼久久 | 青青草无码在线观看 | 亚洲国产中文字幕在线播放 |