aop 使用案例

本文介绍了一种使用AOP注解和Redis单线程缓存机制来防止用户短时间内重复点击的方法。通过在请求地址和参数MD5值上设置缓存并设定过期时间,确保接口在锁定时间内不会被重复调用。代码示例展示了如何创建防止重复提交的注解以及对应的切面处理类,包括参数加密和过期时间设定。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 主要使用场景:

数据比对,本系统数据库内部数据和第三方数据比对是否一致,差别。

因为需要时间比较长,避免用户短时间重复点击问题

aop 通过注解的方式,根据请求地址和参数(md5),使用redis单线程缓存机制,设定过期时间

2. 代码案例

AvoidRepeatSubmit:注解说明,默认5秒
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;


/**
 * 防止重复提交注解
 * @author fanchenbin
 * @since 2022年06月01日18:04:29
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface AvoidRepeatSubmit {
    int lockTime() default 5;
}
RepeatSubmitAspect: 实现类
考虑到参数的各种传参方式,目前只取了传参值加密,没有实现过滤指定参数的方式

如果要实现过滤指定参数的方式,需要格式传参方式单独处理,无法兼容


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tianque.collaboration.annotation.AvoidRepeatSubmit;
import com.tianque.collaboration.common.cache.CacheConstant;
import com.tianque.doraemon.core.tool.api.Result;
import lombok.extern.log4j.Log4j2;
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.aspectj.lang.reflect.MethodSignature;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.xml.bind.DatatypeConverter;
import java.io.BufferedReader;
import java.security.MessageDigest;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Aspect
@Component
@Log4j2
public class RepeatSubmitAspect {

    private final StringRedisTemplate cacheService;

    public RepeatSubmitAspect(StringRedisTemplate cacheService) {
        this.cacheService = cacheService;
    }


    @Pointcut("@annotation(avoidRepeatSubmit)")
    public void pointCut(AvoidRepeatSubmit avoidRepeatSubmit) {

    }

    @Around(value = "pointCut(avoidRepeatSubmit)", argNames = "joinpoint,avoidRepeatSubmit")
    public Object around(ProceedingJoinPoint joinpoint, AvoidRepeatSubmit avoidRepeatSubmit) throws Throwable {
        //锁接口的时长
        int lockSeconds = avoidRepeatSubmit.lockTime();
        MethodSignature methodSignature = (MethodSignature) joinpoint.getSignature();
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
//        Map<String, Object> dataMaps =  commonRequestParamConvert(request);
//        System.out.println(JSON.toJSONString(dataMaps));
        // 获取参数名称
        String methodsName = methodSignature.getMethod().getName();
//        String[] params = methodSignature.getParameterNames();
        //获取参数值
        Object[] args = joinpoint.getArgs();
        StringBuilder content = new StringBuilder();
        if (args != null && args.length > 0) {
            for (Object obj : args) {
                content.append(obj.toString());
            }
        }
        //组合成Redis的KEY
        boolean flag = checkRequest(methodsName, lockSeconds, content.toString());
        //如果缓存中有这个URL,视为重复提交
        if (flag) {
            Object o = joinpoint.proceed();
            return o;
        } else {
            //存在重复请求,直接返回错误
            return Result.fail("系统资源加载中,请勿重复点击!");
        }
    }

    private Map<String, Object> commonRequestParamConvert(HttpServletRequest request) {
        Map<String, Object> params = new HashMap<>();
        try {
            Map<String, String[]> requestParams = request.getParameterMap();
            if (requestParams != null && !requestParams.isEmpty()) {
                requestParams.forEach((key, value) -> params.put(key, value[0]));
            } else {
                StringBuilder paramSb = new StringBuilder();
                try {
                    String str = "";
                    BufferedReader br = request.getReader();
                    while ((str = br.readLine()) != null) {
                        paramSb.append(str);
                    }
                } catch (Exception e) {
                    System.out.println("httpServletRequest get requestbody error, cause : " + e);
                }
                if (paramSb.length() > 0) {
                    JSONObject paramJsonObject = JSON.parseObject(paramSb.toString());
                    if (paramJsonObject != null && !paramJsonObject.isEmpty()) {
                        paramJsonObject.forEach((key, value) -> params.put(key, value));
                    }
                }
            }
        } catch (Exception e) {
            System.out.println("commonRequestParamConvert error, cause : " + e);
        }
        return params;
    }

    public boolean checkRequest(String methodsName, int lockSeconds, String reqJsonParam) {
        String dedupMD5 = jdkMD5(reqJsonParam);
        String key = CacheConstant.KEY_METHOD + methodsName + ":" + dedupMD5;
        // NOTE:直接SETNX不支持带过期时间,所以设置+过期不是原子操作,极端情况下可能设置了就不过期了
        if (!cacheService.hasKey(key)) {
            cacheService.opsForValue().set(key, String.valueOf(0), lockSeconds, TimeUnit.SECONDS);
            return true;
        } else {
            return false;
        }
    }

    public boolean checkRequest(String methodsName, int lockSeconds, String reqJsonParam, String... excludeKeys) {
        String dedupMD5 = dedupParamMD5(reqJsonParam, excludeKeys);
        String key = CacheConstant.KEY_METHOD + methodsName + ":" + dedupMD5;
        // NOTE:直接SETNX不支持带过期时间,所以设置+过期不是原子操作,极端情况下可能设置了就不过期了
        if (!cacheService.hasKey(key)) {
            cacheService.opsForValue().set(key, String.valueOf(0), lockSeconds, TimeUnit.SECONDS);
            return true;
        } else {
            return false;
        }
    }

    public String dedupParamMD5(String reqJSON, String... excludeKeys) {
        TreeMap paramTreeMap = JSON.parseObject(reqJSON, TreeMap.class);
        if (excludeKeys != null) {
            List<String> dedupExcludeKeys = Arrays.asList(excludeKeys);
            if (!dedupExcludeKeys.isEmpty()) {
                for (String dedupExcludeKey : dedupExcludeKeys) {
                    paramTreeMap.remove(dedupExcludeKey);
                }
            }
        }

        String paramTreeMapJSON = JSON.toJSONString(paramTreeMap);
        String md5deDupParam = jdkMD5(paramTreeMapJSON);
        log.debug("md5deDupParam = {}, excludeKeys = {} {}", md5deDupParam, Arrays.deepToString(excludeKeys), paramTreeMapJSON);
        return md5deDupParam;
    }

    private static String jdkMD5(String src) {
        String res = null;
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            byte[] mdBytes = messageDigest.digest(src.getBytes());
            res = DatatypeConverter.printHexBinary(mdBytes);
        } catch (Exception e) {
            log.error("", e);
        }
        return res;
    }
}
TestRequest:测试类

import com.alibaba.fastjson.JSON;
import com.tianque.collaboration.annotation.AvoidRepeatSubmit;
import com.tianque.collaboration.domain.TaskFileLog;
import com.tianque.doraemon.core.tool.api.Result;
import com.tianque.doraemon.mybatis.support.PageParam;
import io.swagger.annotations.Api;
import lombok.extern.log4j.Log4j2;
import org.springframework.web.bind.annotation.*;

/**
 * @Description
 * @Author YuanWeiMin
 * @Date 2022-10-19 10:24
 */
@Log4j2
@Api(tags = "验证接口重复调用【袁伟民】")
@RestController
@RequestMapping("/testRequest")
public class TestRequest {

    @AvoidRepeatSubmit
    @ResponseBody
    @RequestMapping(value = "/testJson", method = RequestMethod.POST)
    public Result taskPassToOtherCountry(@RequestBody TaskFileLog dataMap) throws Exception {
        String result = JSON.toJSONString(dataMap);
        return Result.data(result);
    }

    @AvoidRepeatSubmit
    @ResponseBody
    @RequestMapping(value = "/testParam", method = RequestMethod.POST)
    public Result taskPassToOtherCountry(@RequestParam("result") String result) throws Exception {
        return Result.data(result);
    }

    @AvoidRepeatSubmit
    @ResponseBody
    @RequestMapping(value = "/testBody", method = RequestMethod.POST)
    public Result taskPassToOtherCountry(TaskFileLog taskFileLog, PageParam pageParam) throws Exception {
        return Result.data("ok");
    }
}

### Spring AOP 使用案例与示例代码 #### 日志记录 为了展示如何使用Spring AOP来处理日志记录,在应用程序中可以创建一个切面类用于拦截特定方法并打印进入退出的日志信息。 ```java import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.AfterThrowing; @Aspect public class LoggingAspect { @Before("execution(* com.example.service.*.*(..))") public void logMethodEntry() { System.out.println("Entering method"); } @AfterReturning("execution(* com.example.service.*.*(..))") public void logMethodExit() { System.out.println("Exiting method normally"); } @AfterThrowing(pointcut="execution(* com.example.service.*.*(..))", throwing="ex") public void logException(Exception ex) { System.out.println("Exception occurred: " + ex.getMessage()); } } ``` 此段代码展示了如何定义一个简单的切面来进行基本的日志操作[^1]。 #### 事务管理 当涉及到数据库交互时,确保每次更新都处于有效的事务之中非常重要。下面是一个关于如何配置声明式事务的例子: ```xml <!-- applicationContext.xml --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <!-- all methods starting with 'save' are transactional --> <tx:method name="save*" propagation="REQUIRED"/> <!-- other configurations... --> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut expression="execution(* com.example.dao.*.*(..))" id="daoMethods"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="daoMethods"/> </aop:config> ``` 这段XML片段说明了怎样设置事务属性以及指定哪些DAO层的方法应该被纳入到事务边界之内[^2]。 #### 权限控制 假设有一个安全框架集成的需求,则可以通过AOP轻松实现基于角色的安全性检查。这里给出一段伪代码作为示意: ```java @Aspect @Component public class SecurityAspect { private final RoleService roleService; @Autowired public SecurityAspect(RoleService roleService){ this.roleService = roleService; } @Around("@annotation(Secured)") public Object checkPermission(ProceedingJoinPoint joinPoint, Secured secured) throws Throwable{ String[] allowedRoles = secured.value(); boolean hasPermission = false; // Check user roles against required permissions... if (hasPermission) { return joinPoint.proceed(); // Proceed only when permission is granted. } else { throw new AccessDeniedException("User does not have sufficient privileges."); } } } ``` 上述例子演示了一个环绕通知(`@Around`)的应用场景——即在目标方法之前执行权限验证逻辑;如果用户具备相应权限则继续执行原定流程,反之抛出异常阻止进一步的操作[^5]。 #### 性能监控 对于想要跟踪服务响应时间或者评估系统整体性能的情况来说,也可以借助于AOP技术。如下所示的是测量某个具体API端点耗时时的一个简单实例: ```java @Aspect @Component public class PerformanceMonitorAspect { @Around("within(com.example.controller..*) && execution(public * *(..))") public Object monitorPerformance(ProceedingJoinPoint pjp)throws Throwable { long start = System.currentTimeMillis(); try { return pjp.proceed(); } finally { long elapsedTime = System.currentTimeMillis() - start; System.out.printf("%s took %d ms\n",pjp.getSignature(),elapsedTime); } } } ``` 该方面会自动计算任何匹配路径下的公共HTTP请求所需的时间,并将其输出至标准输出流中[^4]。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值