您好,登錄后才能下訂單哦!
本文小編為大家詳細(xì)介紹“Spring Boot如何防止接口惡意刷新和暴力請(qǐng)求”,內(nèi)容詳細(xì),步驟清晰,細(xì)節(jié)處理妥當(dāng),希望這篇“Spring Boot如何防止接口惡意刷新和暴力請(qǐng)求”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學(xué)習(xí)新知識(shí)吧。
首先創(chuàng)建一個(gè)自定義的攔截器類,也是最核心的代碼;
/** * @package: com.technicalinterest.group.interceptor * @className: IpUrlLimitInterceptor * @description: ip+url重復(fù)請(qǐng)求現(xiàn)在攔截器 * @author: Shuyu.Wang * @date: 2019-10-12 12:34 * @since: 0.1 **/ @Slf4j public class IpUrlLimitInterceptor implements HandlerInterceptor { private RedisUtil getRedisUtil() { return SpringContextUtil.getBean(RedisUtil.class); } private static final String LOCK_IP_URL_KEY="lock_ip_"; private static final String IP_URL_REQ_TIME="ip_url_times_"; private static final long LIMIT_TIMES=5; private static final int IP_LOCK_TIME=60; @Override public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception { log.info("request請(qǐng)求地址uri={},ip={}", httpServletRequest.getRequestURI(), IpAdrressUtil.getIpAdrress(httpServletRequest)); if (ipIsLock(IpAdrressUtil.getIpAdrress(httpServletRequest))){ log.info("ip訪問被禁止={}",IpAdrressUtil.getIpAdrress(httpServletRequest)); ApiResult result = new ApiResult(ResultEnum.LOCK_IP); returnJson(httpServletResponse, JSON.toJSONString(result)); return false; } if(!addRequestTime(IpAdrressUtil.getIpAdrress(httpServletRequest),httpServletRequest.getRequestURI())){ ApiResult result = new ApiResult(ResultEnum.LOCK_IP); returnJson(httpServletResponse, JSON.toJSONString(result)); return false; } return true; } @Override public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { } /** * @Description: 判斷ip是否被禁用 * @author: shuyu.wang * @date: 2019-10-12 13:08 * @param ip * @return java.lang.Boolean */ private Boolean ipIsLock(String ip){ RedisUtil redisUtil=getRedisUtil(); if(redisUtil.hasKey(LOCK_IP_URL_KEY+ip)){ return true; } return false; } /** * @Description: 記錄請(qǐng)求次數(shù) * @author: shuyu.wang * @date: 2019-10-12 17:18 * @param ip * @param uri * @return java.lang.Boolean */ private Boolean addRequestTime(String ip,String uri){ String key=IP_URL_REQ_TIME+ip+uri; RedisUtil redisUtil=getRedisUtil(); if (redisUtil.hasKey(key)){ long time=redisUtil.incr(key,(long)1); if (time>=LIMIT_TIMES){ redisUtil.getLock(LOCK_IP_URL_KEY+ip,ip,IP_LOCK_TIME); return false; } }else { redisUtil.getLock(key,(long)1,1); } return true; } private void returnJson(HttpServletResponse response, String json) throws Exception { PrintWriter writer = null; response.setCharacterEncoding("UTF-8"); response.setContentType("text/json; charset=utf-8"); try { writer = response.getWriter(); writer.print(json); } catch (IOException e) { log.error("LoginInterceptor response error ---> {}", e.getMessage(), e); } finally { if (writer != null) { writer.close(); } } } }
代碼中redis的使用的是分布式鎖的形式,這樣可以最大程度保證線程安全和功能的實(shí)現(xiàn)效果。代碼中設(shè)置的是1S內(nèi)同一個(gè)接口通過同一個(gè)ip訪問5次,就將該ip禁用1個(gè)小時(shí),根據(jù)自己項(xiàng)目需求可以自己適當(dāng)修改,實(shí)現(xiàn)自己想要的功能;
redis分布式鎖的關(guān)鍵代碼:
/** * @package: com.shuyu.blog.util * @className: RedisUtil * @description: * @author: Shuyu.Wang * @date: 2019-07-14 14:42 * @since: 0.1 **/ @Component @Slf4j public class RedisUtil { private static final Long SUCCESS = 1L; @Autowired private RedisTemplate<String, Object> redisTemplate; // =============================common============================ /** * 獲取鎖 * @param lockKey * @param value * @param expireTime:?jiǎn)挝?秒 * @return */ public boolean getLock(String lockKey, Object value, int expireTime) { try { log.info("添加分布式鎖key={},expireTime={}",lockKey,expireTime); String script = "if redis.call('setNx',KEYS[1],ARGV[1]) then if redis.call('get',KEYS[1])==ARGV[1] then return redis.call('expire',KEYS[1],ARGV[2]) else return 0 end end"; RedisScript<String> redisScript = new DefaultRedisScript<>(script, String.class); Object result = redisTemplate.execute(redisScript, Collections.singletonList(lockKey), value, expireTime); if (SUCCESS.equals(result)) { return true; } } catch (Exception e) { e.printStackTrace(); } return false; } /** * 釋放鎖 * @param lockKey * @param value * @return */ public boolean releaseLock(String lockKey, String value) { String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end"; RedisScript<String> redisScript = new DefaultRedisScript<>(script, String.class); Object result = redisTemplate.execute(redisScript, Collections.singletonList(lockKey), value); if (SUCCESS.equals(result)) { return true; } return false; } }
最后將上面自定義的攔截器通過registry.addInterceptor添加一下,就生效了;
@Configuration @Slf4j public class MyWebAppConfig extends WebMvcConfigurerAdapter { @Bean IpUrlLimitInterceptor getIpUrlLimitInterceptor(){ return new IpUrlLimitInterceptor(); } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(getIpUrlLimitInterceptor()).addPathPatterns("/**"); super.addInterceptors(registry); } }
讀到這里,這篇“Spring Boot如何防止接口惡意刷新和暴力請(qǐng)求”文章已經(jīng)介紹完畢,想要掌握這篇文章的知識(shí)點(diǎn)還需要大家自己動(dòng)手實(shí)踐使用過才能領(lǐng)會(huì),如果想了解更多相關(guān)內(nèi)容的文章,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。