防止表单重复提交及AOP环绕通知的使用

防止表单重复提交的后端代码

import java.lang.annotation.*;

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

    int expire() default 5;

}
import cn.hutool.crypto.digest.DigestUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.ixinnuo.common.core.R;
import com.ixinnuo.common.utils.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
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.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Aspect
@Configuration
public class RedisLockMethodInterceptor {

    @Value("${spring.profiles.active}")
    private String springProfilesActive;
    @Value("${spring.application.name}")
    private String springApplicationName;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Pointcut("@annotation(com.aisino.uwcloud.redisLock.RedisLock)")
    public void point() {
    }

    @Around("point()")
    public Object doaround(ProceedingJoinPoint joinPoint) {
        R r = new R();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        RedisLock localLock = method.getAnnotation(RedisLock.class);
        try {
            String lockUniqueKey = getLockUniqueKey(signature, joinPoint.getArgs());

            Integer expire = localLock.expire();
            if (expire < 0) {
                expire = 5;
            }
            ArrayList<String> keys = Lists.newArrayList(lockUniqueKey);
            String result = stringRedisTemplate.execute(setNxWithExpireTime, keys, expire.toString());
            //不存在
            if (!"ok".equalsIgnoreCase(result)) {
                return r.error("不允许重复提交,请稍后再试");
            }
            return joinPoint.proceed();
        } catch (Throwable throwable) {
            throw new RuntimeException(throwable.getMessage());
        }
    }

    /**
     * lua脚本
     */
    private RedisScript<String> setNxWithExpireTime = new DefaultRedisScript<>(
            "return redis.call('set', KEYS[1], 1, 'ex', ARGV[1], 'nx');",
            String.class
    );


    /**
     * 获取唯一标识key
     *
     * @param methodSignature
     * @param args
     * @return
     */
    private String getLockUniqueKey(MethodSignature methodSignature, Object[] args) throws NoSuchAlgorithmException {
        //请求uri, 获取类名称,方法名称
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
        HttpServletRequest request = servletRequestAttributes.getRequest();
        //获取用户信息
        String userId = JWTUtils.getUserId();
        String hash = "";
        List list = new ArrayList();
        if (args.length > 0) {
            String[] parameterNames = methodSignature.getParameterNames();
            for (int i = 0; i < parameterNames.length; i++) {
                Object obj = args[i];
                list.add(obj);
            }
            String param = JSONObject.toJSONString(list);
            hash = DigestUtil.md5Hex(param);
        }
        //项目名称 + 环境编码 + 获取类名称 + 加密参数
        String key = "lock:" + springApplicationName + ":" + springProfilesActive + ":" + userId + ":" + request.getRequestURI();
        if (StringUtils.isNotEmpty(key)) {
            key = key + ":" + hash;
        }

        return key;
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值