springboot防止重复请求提交

亲测!!!
一、自定义注解

import java.lang.annotation.*;

@Inherited
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SameUrlData {
    /**
     * 接口限制时间
     * @return
     */
     long value() default 1000;

}

二、创建拦截器

import com.alibaba.fastjson.JSONObject;
import com.twomantech.caiyuan.common.annotation.SameUrlData;
import com.twomantech.caiyuan.common.enums.ResultCode;
import com.twomantech.caiyuan.common.service.impl.RedisServiceImpl;
import com.twomantech.caiyuan.common.utils.ResultMap;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

/**
 * @Title: 防止用户重复提交数据拦截器
 * @Description: 将用户访问的uri和参数结合token存入redis,每次访问进行验证是否重复请求接口
 */
@Component
public class SameUrlDataInterceptor extends HandlerInterceptorAdapter {

    private static Logger LOG = LoggerFactory.getLogger(SameUrlDataInterceptor.class);
    private static RedisServiceImpl redisServiceImpl;

    /**
     * 是否阻止提交,fasle阻止,true放行
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            SameUrlData annotation = method.getAnnotation(SameUrlData.class);
            if (annotation != null) {
                if(repeatDataValidator(request,annotation.value())){
                    //请求数据相同
                    LOG.warn("please don't repeat submit,url:"+ request.getServletPath());
                    JSONObject result = new JSONObject();
                    result.put("statusCode","500");
                    result.put("message","请勿重复请求");
                    response.setCharacterEncoding("UTF-8");
                    response.setContentType("application/json; charset=utf-8");
                    response.getWriter().write(result.toString());
                    response.getWriter().close();
                    return false;
                }else {
                    //如果不是重复相同数据
                    return true;
                }
            }
            return true;
        } else {
            return super.preHandle(request, response, handler);
        }
    }
    /**
     * 验证同一个url数据是否相同提交,相同返回true
     */
    public boolean repeatDataValidator(HttpServletRequest request, long time){
        if(redisServiceImpl == null){
            WebApplicationContext applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
            redisServiceImpl = applicationContext.getBean(RedisServiceImpl.class);
        }
        String redisKey = request.getRequestURI() + request.getHeader("token");
        String preUrlParams = redisServiceImpl.get(redisKey);
        if(StringUtils.isBlank(preUrlParams)){
            //如果上一个数据为null,表示还没有请求
            redisServiceImpl.set(redisKey,"yes",time,TimeUnit.MILLISECONDS);
            return false;
        }else{
            //否则,已经有过请求
            return true;
        }
    }


}

三、注册拦截器
在WebMvcConfig中注册拦截器,这一段是我截取项目中的,有啥问题可以自行百度springboot拦截器配置(应该没啥问题的)

@Configuration
public class WebMvcConfig  implements WebMvcConfigurer {

 	@Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new SameUrlDataInterceptor());//添加防止重复提交拦截器
	}
}	

四、使用

在需要防止重复请求的方法上加@SameUrlData(毫秒值)

五、关于springboot拦截器中无法注入的问题可以参考https://www.jianshu.com/p/60ff6d0dae7f,上面我是从上下文获取,用static修饰。

参考博客:https://www.cnblogs.com/xhq1024/p/10650127.html

你可能感兴趣的:(java)