Springboot Redis+HandlerInerceptorインタフェースブラシ防止

7642 ワード

説明
コードは他の兄のプロジェクトから剥離され、プロジェクトのアドレスは-https://github.com/wangzaiplus/springboot/tree/wxw必要に応じて記録する
注記の作成
/**
 *               Controller         
 */
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface AccessLimit {

    int maxCount();//       

    int seconds();//     ,   : s

}

ブロッキングの設定
3つのメソッドを含むHandlerInterceptorクラスを実装します.
  • preHanle(HttpServereRequest request,HttpServereResponse response,Object handler)handler実行前呼び出し
  • postHandle(H ttpServeretRequest httpServeretRequest,H ttpServeretResponse httpServeretResponse,Object o,ModelAndView modelAndView)は、業務を処理し、ビューに戻る前に
  • を呼び出す.
  • afterCompletion(H ttpServeretRequest httpServeretRequest,H ttpServeretResponse httpServeretResponse,Object o,Exception e)すべてのものが完了すると
  • が呼び出されます.
    ここではpreHandleを実装するだけです
    /**
     *          
     */
    public class AccessLimitInterceptor implements HandlerInterceptor {
    
        @Autowired
        private JedisUtil jedisUtil;
    
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
            //    Handler  
            if (!(handler instanceof HandlerMethod)) {
                return true;
            }
            
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
    
            //       AccessLimit  
            AccessLimit annotation = method.getAnnotation(AccessLimit.class);
            if (annotation != null) {
                check(annotation, request);
            }
            return true;
        }
        
        //       
        private void check(AccessLimit annotation, HttpServletRequest request) {
            int maxCount = annotation.maxCount();
            int seconds = annotation.seconds();
    
            StringBuilder sb = new StringBuilder();
    
            //        ,  redis     key
            sb.append(Constant.Redis.ACCESS_LIMIT_PREFIX).append(IpUtil.getIpAddress(request)).append(request.getRequestURI());
            String key = sb.toString();
    
            Boolean exists = jedisUtil.exists(key);
            if (!exists) {
                jedisUtil.set(key, String.valueOf(1), seconds);
            } else {
                int count = Integer.valueOf(jedisUtil.get(key));
                if (count < maxCount) {
                    Long ttl = jedisUtil.ttl(key);
                    if (ttl <= 0) {
                        jedisUtil.set(key, String.valueOf(1), seconds);
                    } else {
                        jedisUtil.set(key, String.valueOf(++count), ttl.intValue());
                    }
                } else {
                    throw new ServiceException(ResponseCode.ACCESS_LIMIT.getMsg());
                }
            }
        }
    

    ツールクラス
    JedisUtil:
    @Component
    @Slf4j
    public class JedisUtil {
    
        @Autowired(required = false)
        private JedisPool jedisPool;
    
        private Jedis getJedis() {
            return jedisPool.getResource();
        }
    
        /**
         *   
         *
         * @param key
         * @param value
         * @return
         */
        public String set(String key, String value) {
            Jedis jedis = null;
            try {
                jedis = getJedis();
                return jedis.set(key, value);
            } catch (Exception e) {
                log.error("set key: {} value: {} error", key, value, e);
                return null;
            } finally {
                close(jedis);
            }
        }
    
        /**
         *   
         *
         * @param key
         * @param value
         * @param expireTime     ,   : s
         * @return
         */
        public String set(String key, String value, int expireTime) {
            Jedis jedis = null;
            try {
                jedis = getJedis();
                return jedis.setex(key, expireTime, value);
            } catch (Exception e) {
                log.error("set key:{} value:{} expireTime:{} error", key, value, expireTime, e);
                return null;
            } finally {
                close(jedis);
            }
        }
    
        /**
         *   
         *
         * @param key
         * @param value
         * @return
         */
        public Long setnx(String key, String value) {
            Jedis jedis = null;
            try {
                jedis = getJedis();
                return jedis.setnx(key, value);
            } catch (Exception e) {
                log.error("set key:{} value:{} error", key, value, e);
                return null;
            } finally {
                close(jedis);
            }
        }
    
        /**
         *   
         *
         * @param key
         * @return
         */
        public String get(String key) {
            Jedis jedis = null;
            try {
                jedis = getJedis();
                return jedis.get(key);
            } catch (Exception e) {
                log.error("get key:{} error", key, e);
                return null;
            } finally {
                close(jedis);
            }
        }
    
        /**
         *   key
         *
         * @param key
         * @return
         */
        public Long del(String key) {
            Jedis jedis = null;
            try {
                jedis = getJedis();
                return jedis.del(key.getBytes());
            } catch (Exception e) {
                log.error("del key:{} error", key, e);
                return null;
            } finally {
                close(jedis);
            }
        }
    
        /**
         *   key    
         *
         * @param key
         * @return
         */
        public Boolean exists(String key) {
            Jedis jedis = null;
            try {
                jedis = getJedis();
                return jedis.exists(key.getBytes());
            } catch (Exception e) {
                log.error("exists key:{} error", key, e);
                return null;
            } finally {
                close(jedis);
            }
        }
    
        /**
         *   key    
         *
         * @param key
         * @param expireTime     ,   : s
         * @return
         */
        public Long expire(String key, int expireTime) {
            Jedis jedis = null;
            try {
                jedis = getJedis();
                return jedis.expire(key.getBytes(), expireTime);
            } catch (Exception e) {
                log.error("expire key:{} error", key, e);
                return null;
            } finally {
                close(jedis);
            }
        }
    
        /**
         *       
         *
         * @param key
         * @return
         */
        public Long ttl(String key) {
            Jedis jedis = null;
            try {
                jedis = getJedis();
                return jedis.ttl(key);
            } catch (Exception e) {
                log.error("ttl key:{} error", key, e);
                return null;
            } finally {
                close(jedis);
            }
        }
    
        private void close(Jedis jedis) {
            if (null != jedis) {
                jedis.close();
            }
        }
    
    }
    

    IpUtil:
    public class IpUtil {
    
        /**
         *        ip  
         *
         * @param request
         * @return
         */
        public static String getIpAddress(HttpServletRequest request) {
            String ip = request.getHeader("x-forwarded-for");
    
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
    
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
    
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_CLIENT_IP");
            }
    
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            }
    
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
    
            return ip;
        }
    
    }