0


Redis与自定义注解实现重复

1、创建 SubmitLock 注解

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SubmitLock {
    String key() default "";
}

2、注解实现


    @Autowired
    public RedisUtils redisUtils;

    @Around("execution(* com.example.code_generation..*Controller.*(..)) && @annotation(lock)")
    public Object submitInterceptor(ProceedingJoinPoint pjp, SubmitLock lock) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        HttpServletRequest request = attributes.getRequest();

        String uri = request.getRequestURI();
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
        //真实类名字
        String targetName = pjp.getTarget().getClass().getName();
        //真实方式
        String methodName = pjp.getSignature().getName();
        //所有的请求参数
        Object[] arguments = pjp.getArgs();
        Object[] args = new Object[arguments.length];
        SubmitLock localLock = method.getAnnotation(SubmitLock.class);
        String key = setKey(localLock.key(), pjp.getArgs());

        if (!StringUtils.isEmpty(key)) {
            if (redisUtils.get(key) != null) {
                log.error("请勿重复操作,uri = 【{}】", uri);
                return new RspData<>(BizCodeEnum.WARN, "请勿重复操作");
            }
            redisUtils.set(key,key,2);
        }
        Object result = null;
        try {
            result = pjp.proceed();
            return result;
        }catch (Throwable throwable){
            throw new RuntimeException("服务器异常");
        }finally {
            int order = 0;
            for (Object arg : arguments){
                if (arg instanceof ServletRequest || arg instanceof ServletResponse || arg instanceof MultipartFile){
                    continue;
                }
                args[order] = arg;
                order ++ ;
            }
            log.info("调用Controller方法返回结果,targetName = {}, methodName = {}, args = {}, result = {}",
                    targetName, methodName, args, result);
        }

    }

    private String setKey(String keyExpress, Object[] args) {
        if (null != args && args.length > 0) {
            keyExpress = keyExpress.replace("arg[0]", args[0].toString());
        }
        return keyExpress;
    }

3、controller 测试验证

    @SubmitLock(key = "getTest")
    @ApiOperation(value = "获取代办任务")
    @GetMapping("getTest")
    public Object getTest(@CurrentUser UserInfo userInfo) {
        
    }
标签: redis 前端 javascript

本文转载自: https://blog.csdn.net/lj0910/article/details/136045789
版权归原作者 筱筱木 所有, 如有侵权,请联系我们删除。

“Redis与自定义注解实现重复”的评论:

还没有评论