当前位置:首页 » 《随便一记》 » 正文

SpringBoot防止大量请求攻击_qykhhr的博客

28 人参与  2022年05月09日 15:24  分类 : 《随便一记》  评论

点击全文阅读


我们使用Jmeter测试同学的网站时,就会出现网站无法访问,403等错误。

An error occurred.
Sorry, the page you are looking for is currently unavailable.
Please try again later.

If you are the system administrator of this resource then you should check the error log for details.

Faithfully yours, nginx.

所以我们需要加上IP访问时间限制,防止一个IP多次访问请求,导致整个网站崩溃。

  • 自定义注解:
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 AccessLimit {
    int seconds();
    int maxCount();
    boolean needLogin() default true;
}
  • 自定义拦截器:
    我采用了抛出自定义异常的方式来解决相同IP多次访问的问题:
    throw new DujiaoshouException(20001,"操作过于频繁");
import com.qykhhr.dujiaoshouservice.exceptionhandler.DujiaoshouException;
import com.qykhhr.dujiaoshouservice.mycomment.AccessLimit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * 自定义拦截器
 */
@Component
public class AccessLimtInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (handler instanceof HandlerMethod) {
            HandlerMethod hm = (HandlerMethod) handler;
            AccessLimit accessLimit = hm.getMethodAnnotation(AccessLimit.class);
            if (null == accessLimit) {
                return true;
            }
            int seconds = accessLimit.seconds();
            int maxCount = accessLimit.maxCount();
            boolean needLogin = accessLimit.needLogin();

            if (needLogin) {
                //判断是否登录
            }
            String ip=request.getRemoteAddr();
            String key = request.getServletPath() + ":" + ip ;
            Integer count = (Integer) redisTemplate.opsForValue().get(key);

            if (null == count || -1 == count) {
                redisTemplate.opsForValue().set(key, 1,seconds, TimeUnit.SECONDS);
                return true;
            }

            if (count < maxCount) {
                count = count+1;
                redisTemplate.opsForValue().set(key, count,0);
                return true;
            }

            //  response 返回 json 请求过于频繁请稍后再试
            throw new DujiaoshouException(20001,"操作过于频繁");
        }

        return true;
    }
}
  • 在webconfig中配置拦截器

import com.qykhhr.dujiaoshouservice.Interceptor.AccessLimtInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * 在webconfig中配置拦截器
 */
@Configuration
public class MyWebMvcConfigurer extends WebMvcConfigurerAdapter {

    @Autowired
    private AccessLimtInterceptor accessLimtInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(accessLimtInterceptor);
        super.addInterceptors(registry);
    }
}

  • 在Controller前面加上注解就可以生效了
@RestController
public class AppHomeController {

    @GetMapping("/index")
    @AccessLimit(seconds = 1, maxCount = 3) //1秒内 允许请求3次
    public R getImageList(){
        return R.ok().data("appHome","hahaha");
    }
}

使用python发送100次请求,可以发现请求被拦截了多少
在这里插入图片描述
对于注解,我们也可以不使用它,但是我们需要在拦截器中写入固定的参数。


点击全文阅读


本文链接:http://zhangshiyu.com/post/39784.html

自定义  请求  注解  
<< 上一篇 下一篇 >>

  • 评论(0)
  • 赞助本站

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

最新文章

  • 整容99次,归来做未婚妻后爸大结局_姜茜柳眉姜小姐抖音热门_小说后续在线阅读_无删减免费完结_
  • 朝徽宜燕澹容是什么小说(难搞!燕总又争又抢)(朝徽宜燕澹容)全本完整清爽版在线+无广告结局
  • 重生后我去扫厕所,鉴宝女神却疯了阅读_帝王小姐陈列精校文本_小说后续在线阅读_无删减免费完结_
  • 鹤不归顾宁喧林绾绾完结篇(顾宁喧林绾绾)全篇免费版在线+无障碍结局
  • 终章小说简明月顾烬深完结篇(你走后月光沉入深海)已更新+延伸(简明月顾烬深)清爽版
  • 我死后前夫疯魔了全书阮星舟霍景时在线
  • 救命!我被痴女包围了!列表_救命!我被痴女包围了!(神岛裕树)
  • 被亲姐封印百年,她死后我覆灭三界优质全文_封印小老仙老夫新上热文_小说后续在线阅读_无删减免费完结_
  • 全文七零香江,玄学大佬靠算命发家致富(柳玄黄招娣)列表_全文七零香江,玄学大佬靠算命发家致富
  • 七零娇娇美又媚,冷硬糙汉逃不掉续集(纪淮宋安宁)全本完整免费版_起点章节+后续(七零娇娇美又媚,冷硬糙汉逃不掉)
  • 重活一世,我钓到了真正的顾家家主热门推荐_顾星伯父顾星承阅读_小说后续在线阅读_无删减免费完结_
  • 重生之团长老公才是白月光小说(蒋横波姚沐兰)外篇+结局(重生之团长老公才是白月光)全篇在线阅读

    关于我们 | 我要投稿 | 免责申明

    Copyright © 2020-2022 ZhangShiYu.com Rights Reserved.豫ICP备2022013469号-1