IT俱乐部 Redis Redis与自定义注解实现重复方式

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) {
        
    }

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持IT俱乐部。

本文收集自网络,不代表IT俱乐部立场,转载请注明出处。https://www.2it.club/database/redis/17508.html
上一篇
下一篇
联系我们

联系我们

在线咨询: QQ交谈

邮箱: 1120393934@qq.com

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

返回顶部