springboot基于aop+redis实现防止重复提交

首先定义一个自定义注解

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 可以防止表单提交的注解
 */
@Retention(RetentionPolicy.RUNTIME)//指定该注解在运行时可以获取
@Target(ElementType.METHOD)//该注解执行当前注解可以作用的范围
public @interface AvoidRepeatableCommit {
    /**
     * 指定时间内不可重复提交,单位毫秒 default 3000默认为三秒
     */
    long timeout()  default 3000 ;
}

 定义一个切面类

对于连接点 切点 增强的理解
//join point 代表连接点 springboot项目中的所有方法 都有可能成为被切入的点
//point cut 代表一个切入点 标注这个注解的所有方法
//advice  表示增强  before after around 表示被切入的点增强功能(也就是要按切入时机 执行增强方法)
import com.shkj.partsstock.common.Result;
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.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
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 java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

@Aspect
@Component
@Slf4j
public class AvoidRepeatableCommitAspect{

    @Autowired
    private RedisTemplate redisTemplate;

    @Around("@annotation(com.shkj.partsstock.test.test1.AvoidRepeatableCommit)")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        String ip = IPUtils.getIpAddr(request);//获取客户端请求的ip地址
        log.debug("客户端ip地址:" + ip);
        //获取到注解信息
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        //获取目标类,方法
        String name = method.getName();//获取方法名
        String className = method.getDeclaringClass().getName();//获取类名称
        String ipKey = className + "#" +name;
        log.debug("类名与方法名的hashCode值:"+ipKey.hashCode());
        int keyHashCode = Math.abs(ipKey.hashCode());
        String key = "ECCOM:arc-" + ip +"-"+ keyHashCode;
        log.info("ipKey={},keyHashCode={},key={}",ipKey,keyHashCode,key);
        AvoidRepeatableCommit avoidRepeatableCommit = method.getAnnotation(AvoidRepeatableCommit.class);
        long timeout = avoidRepeatableCommit.timeout();
        if (timeout < 0 ){
            timeout = 3 * 1000L;
        }
        String value = (String) redisTemplate.opsForValue().get(key);
        if (StringUtils.isNotBlank(value)){
            return Result.fail(303,"请勿重复提交!",null);
        }
        redisTemplate.opsForValue().set(key, UUIDUtils.getUUID(),timeout, TimeUnit.MILLISECONDS);
        Object proceed = point.proceed();
        return proceed;
    }
}

统一结果返回Result
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Result implements Serializable {

	private int code;
	private String message;
	private Object data;

	public static Result succ(Object data) {
		return succ(200, "操作成功", data);
	}

	public static Result succ(int code, String msg, Object data) {
		Result r = new Result();
		r.setCode(code);
		r.setMessage(msg);
		r.setData(data);
		return r;
	}

	public static Result fail(String msg) {
		return fail(400, msg, null);
	}

	public static Result fail(int code, String msg, Object data) {
		Result r = new Result();
		r.setCode(code);
		r.setMessage(msg);
		r.setData(data);
		return r;
	}



}
IPUtils工具类
package com.shkj.partsstock.test.test1;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;


public class IPUtils {

    private static Logger logger = LoggerFactory.getLogger(IPUtils.class);

    /**
     * 获取IP地址
     * 使用Nginx等反向代理软件, 则不能通过request.getRemoteAddr()获取IP地址
     * 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,X-Forwarded-For中第一个非unknown的有效IP字符串,则为真实IP地址
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = null;
        try {
            ip = request.getHeader("x-forwarded-for");
            if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if (StringUtils.isEmpty(ip) || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_CLIENT_IP");
            }
            if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            }
            if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
        } catch (Exception e) {
            logger.error("IPUtils ERROR ", e);
        }
        // 使用代理,则获取第一个IP地址
        if (StringUtils.isEmpty(ip) && ip.length() > 15) {
            if (ip.indexOf(",") > 0) {
                ip = ip.substring(0, ip.indexOf(","));
            }
        }
        return ip;
    }
}

getUUID工具类
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 *
 * @TODO: 生成随机字符串的工具类 uuid
 */
@Component
public class UUIDUtils {

    public static String getUUID(){
        return UUID.randomUUID().toString().replace("-", "");
    }

    public static void main(String[] args) {
        System.out.println("格式前的UUID : " + UUID.randomUUID().toString());
        System.out.println("格式化后的UUID :" + getUUID());
    }
}

测试


    @AvoidRepeatableCommit
    @PostMapping("/test/addData")
    public Result addData(){
        //String s = testService.testMethod();
        return Result.succ("成功提交");
    }

你可能感兴趣的:(redis,spring,boot,java)