• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

springboot结合ehcache防止恶意刷新请求的实现

springboot 搞代码 4年前 (2022-01-05) 20次浏览 已收录 0个评论

这篇文章主要介绍了springboot结合ehcache防止恶意刷新请求的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

说明

我们在把开发好的网站上线之前一定要考虑到别人恶意刷新你的网页这种情况,最大限度的去限制他们。否则往往这将搞垮你的应用服务器,想象一下某个恶意用户利用众多肉鸡在1分钟内请求你网页几十万次是个什么情形?
部分内容参考网络。

要达到什么效果?

我限制请求的用户,根据来访IP去记录它N分钟之内请求单一网页的次数,如果超过N次我就把这个IP添加到缓存黑名单并限制它3小时之内无法访问类型网页。

效果图

1分钟内请求单网页超过15次就被加入黑名单,冻结3小时!

开发步骤

  • 采用AOP+Ehcache方式。(Redis也可以)
  • AOP用于拦截和逻辑判断,Ehcache负责计数和缓存。

配置ehcache

略。

创建注解

 @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @Documented @Order(Ordered.HIGHEST_PRECEDENCE) public @interface RequestLimit { /** * 允许访问的最大次数 */ int count() default 15; /** * 时间段,单位为毫秒,默认值一分钟 */ long time() default 1000*60; }

创建AOP

 @Aspect @Component public class RequestLimitAspect { private static final Logger logger = LoggerFactory.getLogger(RequestLimit.class);<strong style="color:transparent">来源gaodaima#com搞(代@码网</strong> @Autowired EhcacheUtil ehcacheUtil; @Before("within(@org.springframework.stereotype.Controller *) && @annotation(limit)") public void requestLimit(final JoinPoint joinPoint , RequestLimit limit) throws RequestLimitException { try { Object[] args = joinPoint.getArgs(); HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); String ip = IpUtil.getRemoteIp(request); String uri = request.getRequestURI().toString(); String key = "req_"+uri+"_"+ip; String blackKey = "black_"+ip; // 黑名单IP封锁一段时间 int count = 0; // 访问次数 // 判断是否在黑名单 if (ehcacheUtil.contains("countcache",blackKey)){ throw new RequestLimitException(); }else{ // 判断是否已存在访问计数 if (!ehcacheUtil.contains("limitCache",key)) { ehcacheUtil.put("limitCache",key,1); } else { count = ehcacheUtil.getInt("limitCache",key)+1; ehcacheUtil.put("limitCache",key,count); if (count > limit.count()) { logger.info("用户IP[" + ip + "]访问地址[" + uri + "]超过了限定的次数[" + limit.count() + "]"); // 加入黑名单 ehcacheUtil.put("countcache",blackKey,"badguy"); throw new RequestLimitException(); } } } }catch (RequestLimitException e){ throw e; }catch (Exception e){ logger.error("发生异常",e); } } }

应用aop

找到要应用的接口加上注解@RequestLimit即可。

 @RequestLimit(count=10) @OperLog(operModule = "更多文章",operType = "查询",operDesc = "查询更多文章") @GetMapping("/more/{categoryId}") public String getMore(@PathVariable("categoryId") String categoryId, Model model, HttpServletRequest request) { // 略 }

到此这篇关于springboot结合ehcache防止恶意刷新请求的实现的文章就介绍到这了,更多相关springboot 防止恶意刷新内容请搜索gaodaima搞代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持gaodaima搞代码网

以上就是springboot结合ehcache防止恶意刷新请求的实现的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:springboot结合ehcache防止恶意刷新请求的实现

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址