目录
  • 前言
  • 思路分析
  • 具体实现
    • 编写 RedisUtils
    • 定义Interceptor
  • 改进

    前言

    我们在浏览网站后台的时候,假如我们频繁请求,那么网站会提示 “请勿重复提交” 的字样,那么这个功能究竟有什么用呢,又是如何实现的呢?

    其实这就是接口防刷的一种处理方式,通过在一定时间内限制同一用户对同一个接口的请求次数,其目的是为了防止恶意访问导致服务器和数据库的压力增大,也可以防止用户重复提交。

    思路分析

    接口防刷有很多种实现思路,例如:拦截器/AOP+Redis、拦截器/AOP+本地缓存、前端限制等等很多种实现思路,在这里我们来讲一下 拦截器+Redis 的实现方式。

    其原理就是 在接口请求前由拦截器拦截下来,然后去 redis 中查询是否已经存在请求了,如果不存在则将请求缓存,若已经存在则返回异常。具体可以参考下图

    教你实现Java接口防刷

    具体实现

    注:以下代码中的 AjaxResult 为统一返回对象,这里就不贴出代码了,大家可以根据自己的业务场景来编写。

    编写 RedisUtils

    import com.apply.core.exception.MyRedidsException;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.stereotype.Component;
    import org.springframework.util.CollectionUtils;
    
    import java.util.Collections;
    import java.util.List;
    import java.util.Map;
    import java.util.Set;
    import java.util.concurrent.TimeUnit;
    
    /**
     * Redis工具类
     */
    @Component
    public class RedisUtils {
    
        @Autowired
        private RedisTemplate<String, Object> redisTemplate;
    
        /****************** common start ****************/
        /**
         * 指定缓存失效时间
         *
         * @param key  键
         * @param time 时间(秒)
         * @return
         */
        public boolean expire(String key, long time) {
            try {
                if (time > 0) {
                    redisTemplate.expire(key, time, TimeUnit.SECONDS);
                }
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    
        /**
         * 根据key 获取过期时间
         *
         * @param key 键 不能为null
         * @return 时间(秒) 返回0代表为永久有效
         */
        public long getExpire(String key) {
            return redisTemplate.getExpire(key, TimeUnit.SECONDS);
        }
    
        /**
         * 判断key是否存在
         *
         * @param key 键
         * @return true 存在 false不存在
         */
        public boolean hasKey(String key) {
            try {
                return redisTemplate.hasKey(key);
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    
        /**
         * 删除缓存
         *
         * @param key 可以传一个值 或多个
         */
        @SuppressWarnings("unchecked")
        public void del(String... key) {
            if (key != null && key.length > 0) {
                if (key.length == 1) {
                    redisTemplate.delete(key[0]);
                } else {
                    redisTemplate.delete(CollectionUtils.arrayToList(key));
                }
            }
        }
        /****************** common end ****************/
    
    
        /****************** String start ****************/
    
        /**
         * 普通缓存获取
         *
         * @param key 键
         * @return 值
         */
        public Object get(String key) {
            return key == null ? null : redisTemplate.opsForValue().get(key);
        }
    
        /**
         * 普通缓存放入
         *
         * @param key   键
         * @param value 值
         * @return true成功 false失败
         */
        public boolean set(String key, Object value) {
            try {
                redisTemplate.opsForValue().set(key, value);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    
        /**
         * 普通缓存放入并设置时间
         *
         * @param key   键
         * @param value 值
         * @param time  时间(秒) time要大于0 如果time小于等于0 将设置无限期
         * @return true成功 false 失败
         */
        public boolean set(String key, Object value, long time) {
            try {
                if (time > 0) {
                    redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
                } else {
                    set(key, value);
                }
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    
        /**
         * 递增
         *
         * @param key   键
         * @param delta 要增加几(大于0)
         * @return
         */
        public long incr(String key, long delta) {
            if (delta < 0) {
                throw new MyRedidsException("递增因子必须大于0");
            }
            return redisTemplate.opsForValue().increment(key, delta);
        }
    
        /**
         * 递减
         *
         * @param key   键
         * @param delta 要减少几(小于0)
         * @return
         */
        public long decr(String key, long delta) {
            if (delta < 0) {
                throw new MyRedidsException("递减因子必须大于0");
            }
            return redisTemplate.opsForValue().increment(key, -delta);
        }
        /****************** String end ****************/
    }
    

    定义Interceptor

    import com.alibaba.fastjson.JSON;
    import com.apply.common.utils.redis.RedisUtils;
    import com.apply.common.validator.annotation.AccessLimit;
    import com.apply.core.http.AjaxResult;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Component;
    import org.springframework.web.method.HandlerMethod;
    import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
    
    import javax.servlet.ServletOutputStream;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import java.util.Objects;
    
    /**
     * @description 重复请求拦截
     * @date 2023-08-13 14:14
     */
    @Component
    public class RepeatRequestIntercept extends HandlerInterceptorAdapter {
    
        @Autowired
        private RedisUtils redisUtils;
    
        /**
         * 限定时间 单位:秒
         */
        private final int seconds = 1;
    
        /**
         * 限定请求次数
         */
        private final int max = 1;
    
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            //判断请求是否为方法的请求
            if (handler instanceof HandlerMethod) {
                String key = request.getRemoteAddr() + "-" + request.getMethod() + "-" + request.getRequestURL();
                Object requestCountObj = redisUtils.get(key);
                if (Objects.isNull(requestCountObj)) {
                    //若为空则为第一次请求
                    redisUtils.set(key, 1, seconds);
                } else {
                    response.setContentType("application/json;charset=utf-8");
                    ServletOutputStream os = response.getOutputStream();
                    AjaxResult<Void> result = AjaxResult.error(100, "请求已提交,请勿重复请求");
                    String jsonString = JSON.toJSONString(result);
                    os.write(jsonString.getBytes());
                    os.flush();
                    os.close();
                    return false;
                }
            }
            return true;
        }
    
    }
    

    然后我们 将拦截器注册到容器中

    import com.apply.common.validator.intercept.RepeatRequestIntercept;
    import com.apply.core.base.entity.Constants;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.CorsRegistry;
    import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
    import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    
    /**
     * @description 
     * @date 2023-08-13 14:17
     */
    @Configuration
    public class WebConfig implements WebMvcConfigurer {
    
        @Autowired
        private RepeatRequestIntercept repeatRequestIntercept;
    
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(repeatRequestIntercept);
        }
    }
    

    我们再来编写一个接口用于测试

    import com.apply.common.validator.annotation.AccessLimit;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    /**
     * @description
     * @date 2023-08-13 14:35
     */
    @RestController
    public class TestController {
    
        @GetMapping("/test")
        public String test(){
            return "SUCCESS";
        }
    
    }
    

    最后我们来看一下结果是否符合我们的预期:

    1秒内的第一次请求:

    教你实现Java接口防刷

    1秒内的第二次请求:

    教你实现Java接口防刷

    确实已经达到了我们的预期,但是如果我们对特定接口进行拦截,或对不同接口的限定拦截时间和次数不同的话,这种实现方式无法满足我们的需求,所以我们要提出改进。

    改进

    我们可以去写一个自定义的注解,并将 seconds 和 max 设置为该注解的属性,再在拦截器中判断请求的方法是否包含该注解,如果包含则执行拦截方法,如果不包含则直接返回。
    自定义注解 RequestLimit

    import java.lang.annotation.ElementType;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.Target;
    
    /**
     * @description 幂等性注解
     * @date 2023-08-13 15:10
     */
    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.METHOD)
    public @interface RequestLimit {
    
        /**
         * 限定时间
         */
        int seconds() default 1;
    
        /**
         * 限定请求次数
         */
        int max() default 1;
    
    }
    

    改进 RepeatRequestIntercept

    /**
     * @description 重复请求拦截
     * @date 2023-08-13 15:14
     */
    @Component
    public class RepeatRequestIntercept extends HandlerInterceptorAdapter {
    
        @Autowired
        private RedisUtils redisUtils;
    
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            //判断请求是否为方法的请求
            if (handler instanceof HandlerMethod) {
                HandlerMethod hm = (HandlerMethod) handler;
                //获取方法中是否有幂等性注解
                RequestLimit anno = hm.getMethodAnnotation(RequestLimit.class);
                //若注解为空则直接返回
                if (Objects.isNull(anno)) {
                    return true;
                }
                int seconds = anno.seconds();
                int max = anno.max();
                String key = request.getRemoteAddr() + "-" + request.getMethod() + "-" + request.getRequestURL();
                Object requestCountObj = redisUtils.get(key);
                if (Objects.isNull(requestCountObj)) {
                    //若为空则为第一次请求
                    redisUtils.set(key, 1, seconds);
                } else {
                    //限定时间内的第n次请求
                    int requestCount = Integer.parseInt(requestCountObj.toString());
                    //判断是否超过最大限定请求次数
                    if (requestCount < max) {
                        //未超过则请求次数+1
                        redisUtils.incr(key, 1);
                    } else {
                        //否则拒绝请求并返回信息
                        refuse(response);
                        return false;
                    }
                }
            }
            return true;
        }
    
        /**
         * @date 2023-08-14 15:25
         * @author Bummon
         * @description 拒绝请求并返回结果
         */
        private void refuse(HttpServletResponse response) throws IOException {
            response.setContentType("application/json;charset=utf-8");
            ServletOutputStream os = response.getOutputStream();
            AjaxResult<Void> result = AjaxResult.error(100, "请求已提交,请勿重复请求");
            String jsonString = JSON.toJSONString(result);
            os.write(jsonString.getBytes());
            os.flush();
            os.close();
        }
    
    }
    

    这样我们就可以实现我们的需求了。

    声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。