美文网首页SpringSpringFramework
使用spring interceptor拦截器实现API并发调用

使用spring interceptor拦截器实现API并发调用

作者: 王帅199207 | 来源:发表于2017-08-04 16:06 被阅读274次

    限流拦截器辅助类,用于存储每个请求的并发访问数:

    /**
     * @date 2017年8月4日
     */
    package com.wedoctor.health.card.cloud.api.home.interceptor;
    
    import java.util.concurrent.ConcurrentHashMap;
    import java.util.concurrent.atomic.AtomicInteger;
    
    /**
     * 限流拦截器辅助类,用于存储每个请求的访问数
     * @author wangshuai
     * @date 2017年8月4日
     */
    public class AccessCounts {
    
        /**
         * 统计KEY值
         */
        public static final String URL = "AccessCounts.URL";
        /**
         * 并发计数
         */
        private ConcurrentHashMap<Object, AtomicInteger> map = new ConcurrentHashMap<>();
    
        //静态内部类实现单例
        private AccessCounts() {
            
        }
    
        private static class Instance {
            static AccessCounts counts = new AccessCounts();
        }
    
        public static AccessCounts getInstance() {
            return Instance.counts;
        }
    
        /**
         * 获取对应api的访问次数
         * @param key
         * @return
         */
        public int get(Object key) {
            AtomicInteger counter = map.get(key);
            if (counter == null) {
                counter = new AtomicInteger(0);
                AtomicInteger c = map.putIfAbsent(key, counter);
                if(c != null) {
                    counter = c;
                }
            }
            return counter.intValue();
        }
    
        /**
         * 自增1
         * @param key
         * @return
         */
        public int incrementAndGet(Object key) {
            AtomicInteger counter = map.get(key);
            if (counter == null) {
                counter = new AtomicInteger(0);
                AtomicInteger c = map.putIfAbsent(key, counter);
                if(c != null) {
                    counter = c;
                }
            }
            return counter.incrementAndGet();
        }
    
        /**
         * 自减1
         * @param key
         * @return
         */
        public int decrementAndGet(Object key) {
            AtomicInteger counter = map.get(key);
            if (counter == null) {
                return 0;
            }
            return counter.decrementAndGet();
        }
        
    }
    
    

    拦截器代码:

    /**
     * @date 2017年8月4日
     */
    package com.wedoctor.health.card.cloud.api.home.interceptor;
    
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.net.URL;
    import java.net.URLConnection;
    import java.util.Timer;
    import java.util.TimerTask;
    import java.util.concurrent.ConcurrentHashMap;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.apache.log4j.Logger;
    import org.apache.log4j.MDC;
    import org.springframework.web.method.HandlerMethod;
    import org.springframework.web.servlet.ModelAndView;
    import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
    
    /**
     * 限流拦截器
     * 
     * @author wangshuai
     * @date 2017年8月4日
     */
    public class InServiceAccessInterceptor extends HandlerInterceptorAdapter {
    
        private static final Logger logger = Logger.getLogger(InServiceAccessInterceptor.class);
    
        /**
         * 配置信息
         */
        private ConcurrentHashMap<String, Integer> config = new ConcurrentHashMap<String, Integer>();
    
        /**
         * 默认的限制次数
         */
        private int defaultLimit = 100;
    
        /**
         * 配置文件的URL
         */
        private String configUrl = null;
        
        /**
         * 加载配置文件的频率
         */
        private int loadInterval = 1, loadDelay = 5;
        
        /**
         * 是否合法
         */
        private boolean valid;
    
        /**
         * 拦截器构造函数, 传入的参数在xml中配置
         * @param defaultLimit
         * @param configUrl
         * @param loadInterval
         * @param loadDelay
         * @param valid
         */
        public InServiceAccessInterceptor(int defaultLimit, String configUrl, int loadInterval, int loadDelay, boolean valid) {
            this.defaultLimit = defaultLimit;
            this.configUrl = configUrl;
            this.loadInterval = loadInterval;
            this.loadDelay = loadDelay;
            this.valid = valid;
            if (valid) {
                task();
            }
        }
    
        /**
         * 拦截器逻辑
         */
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            if (valid) {
                if (handler instanceof HandlerMethod) {
                    HandlerMethod handlerMethod = (HandlerMethod) handler;
                    String callpath = handlerMethod.getMethod().getDeclaringClass().getSimpleName() + "."
                            + handlerMethod.getMethod().getName();
                    System.out.println(callpath);
                    int counter = AccessCounts.getInstance().get(callpath);
                    boolean limit = limit(callpath, counter);
                    if (limit) {
                        throw new IllegalAccessException("调用次数超出限制." + callpath + "=" + counter);
                    }
                    MDC.put(AccessCounts.CALLPATH, callpath);
                    AccessCounts.getInstance().incrementAndGet(callpath);
                }
            }
            return true;
        }
    
        /**
         * 每次执行完后,清除计数,实现限制同一个API同时调用的次数
         */
        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
            if (valid) {
                Object callpath = MDC.get(AccessCounts.CALLPATH);
                if (null != callpath) {
                    AccessCounts.getInstance().decrementAndGet(callpath);
                }
                MDC.remove(AccessCounts.CALLPATH);
            }
        }
    
        /**
         * 
         */
        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
                throws Exception {
            // TODO Auto-generated method stub
    
        }
    
        /**
         * 判断是否超出限制次数
         * @date 2017年8月4日
         * @author wangshuai
         * @param callpath
         * @param counter
         * @return
         */
        private boolean limit(String callpath, int counter) {
            //每次都从配置中读取限制的次数
            Integer obj = config.get(callpath);
            int limit = defaultLimit;
            if (obj != null) {
                limit = obj.intValue();
            }
            System.out.println("check callpath:" + callpath + " limit:" + limit + " counter:" + counter);
            if (logger.isDebugEnabled()) {
                logger.debug("check callpath:" + callpath + " limit:" + limit + " counter:" + counter);
            }
            if (counter >= limit) {
                System.out.println("the call[" + callpath + "] is over limit:" + limit + " counter:" + counter);
                logger.warn("the call[" + callpath + "] is over limit:" + limit + " counter:" + counter);
                return true;
            }
            return false;
        }
    
        /**
         * 定时更新拦截器配置
         * @date 2017年8月4日
         * @author wangshuai
         */
        public void task() {
            TimerTask task = new TimerTask() {
                @Override
                public void run() {
                    if (null == configUrl)
                        return;
                    String text = sendGet(configUrl, null);
                    logger.info("load config:" + text);
                    if (null == text || "".equals(text.trim()))
                        return;
    
                    text = text.replaceAll("[\\{\\}\"\n]", "");
                    config.clear();
                    for (String line : text.split(",")) {
                        String fields[] = line.split(":");
                        if (fields.length < 2)
                            continue;
                        try {
                            config.put(fields[0].trim(), Integer.valueOf(fields[1].trim()));
                        } catch (Exception e) {
                            logger.error("load config fail.", e);
                        }
                    }
                }
            };
            Timer timer = new Timer();
            long delay = 1000 * loadDelay;
            long intevalPeriod = 1000 * loadInterval;
            // schedules the task to be run in an interval
            logger.info("Task setting  delay:" + delay + "  intevalPeriod:" + intevalPeriod);
            timer.scheduleAtFixedRate(task, delay, intevalPeriod);
    
            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        try {
                            Thread.sleep(60 * 1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println("AccessCounts status:" + AccessCounts.getInstance().status());
                    }
                }
            }).start();
        }
        
        /**
         *  从url中获取配置字符串
         */
        public static String sendGet(String url, String param) {
            String result = "";
            BufferedReader in = null;
            try {
                String urlNameString = url + (param == null ? "" : "?" + param);
                URL realUrl = new URL(urlNameString);
                // 打开和URL之间的连接
                URLConnection connection = realUrl.openConnection();
                // 设置通用的请求属性
                connection.setRequestProperty("accept", "*/*");
                connection.setRequestProperty("connection", "Keep-Alive");
                connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
                // 建立实际的连接
                connection.connect();
                // 获取所有响应头字段
                /*
                 * Map<String, List<String>> map = connection.getHeaderFields(); for
                 * (String key : map.keySet()) { System.out.println(key + "--->" +
                 * map.get(key)); }
                 */
                // 定义 BufferedReader输入流来读取URL的响应
                in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String line;
                while ((line = in.readLine()) != null) {
                    result += line;
                }
            } catch (Exception e) {
                logger.error("request url fail=" + url, e);
            }
            // 使用finally块来关闭输入流
            finally {
                try {
                    if (in != null) {
                        in.close();
                    }
                } catch (Exception e) {
                }
            }
            return result;
        }
    
    }
    
    

    xml配置:

        <mvc:interceptors>    
            <mvc:interceptor>    
                <mvc:mapping path="/**" />    
                <bean class="com.wedoctor.health.card.cloud.api.home.interceptor.InServiceAccessInterceptor" >    
                    <constructor-arg index="0" value="5" /> <!-- defaultLimit 默认设置 -->    
                    <constructor-arg index="1" value="http://localhost/web.limit" /> <!-- configUrl    -->    
                    <constructor-arg index="2" value="60" /> <!-- loadInterval unit : second -->    
                    <constructor-arg index="3" value="5" /> <!-- loadDelay unit : second -->    
                    <constructor-arg index="4" value="true" /> <!-- valid  true: used -->    
                </bean>    
            </mvc:interceptor>    
        </mvc:interceptors>   
    

    http://localhost/web.limit配置文件内容:

    {"IndexController.index":500,
    "ProductController.searchProducts":500
    }
    

    相关文章

      网友评论

      • 一帅:public int incrementAndGet(Object key) {
        AtomicInteger counter = map.get(key);
        if (counter == null) {
        counter = new AtomicInteger(0);
        map.put(key, counter);
        }
        return counter.incrementAndGet();
        }

        这行代码有线程安全问题
        王帅199207:@藤伦柳揶 已经改了
        一帅:@王帅199207 最好还是更新一下吧
        王帅199207:谢谢提醒,这段其实以前发现改掉了,文章里面忘记更新

      本文标题:使用spring interceptor拦截器实现API并发调用

      本文链接:https://www.haomeiwen.com/subject/kvtblxtx.html