zoukankan      html  css  js  c++  java
  • 实例:接口并发限流RateLimiter

    需求:接口每秒最多只能相应1个请求

    1.创建 全局类对象

    import com.google.common.util.concurrent.RateLimiter;
    import org.springframework.stereotype.Service;
    
    /**
     * @Auther: 011336
     * @Date: 2019/4/29 17:31
     */
    @Service
    public class AccessLimitService {
        /**
         * 每秒只发出1个令牌
         */
        RateLimiter rateLimiter = RateLimiter.create(1.0);
    
        /**
         * 获取等待时间 方法阻塞
         * 每次等待一个获取一个令牌
         * @return
         */
        public double acquire(){
            double waitTime = rateLimiter.acquire(1);
            return waitTime;
        }
    }

    2.测试实例  模拟10个并发请求

    @Controller
    @RequestMapping("/SegmentRecommend")
    public class NearestAirportController {
    
        private Logger logger = Logger.getLogger(NearestAirportController.class);
    
        @Autowired
        private NearestAirportService nearestAirportService;
    
        @Autowired
        private AccessLimitService accessLimitService;
    
        /**
       * 此方法是我们对外提供的接口,通过调用acquire()方法获取令牌,获取失时会阻塞直到获取令牌成功才继续执行
       */
    public ModelAndView getNearestAirport(HttpServletRequest request, HttpServletResponse response)throws Exception { logger.info("NearestAirportController.getNearestAirport begin"); System.out.println(" |||||||||||||waitTime:" + accessLimitService.acquire()); RemoteAirportsData data = nearestAirportService.getNearestAirports(); logger.info("NearestAirportController.getNearestAirport end"); return null; } @RequestMapping(value ="/GetNearestAirport" ,produces = "application/json;charset=UTF-8") public ModelAndView ttttt (HttpServletRequest request, HttpServletResponse response) throws Exception{ logger.info("============================================================================="); ExecutorService fixedThreadPool = Executors.newFixedThreadPool(10);
        //开启10个线程模拟10个并发请求
    for(int i=0;i<10;i++) { fixedThreadPool.submit(new Runnable() { @Override public void run() { try { getNearestAirport(request,response); } catch (Exception e) { e.printStackTrace(); } } }); } fixedThreadPool.shutdown(); fixedThreadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS); logger.info("================================================================================"); return null; } }

    3. 执行结果:getNearestAirpor()方法每秒只执行了一次

    总结:关键是要让  rateLimiter  变量成为线程共享变量,每个请求执行前都要来到 rateLimiter 中获取令牌。成功择执行,失败则阻塞 直到拿到令牌才继续执行

  • 相关阅读:
    Oracle varchar2最大支持长度(转)
    Java 内存溢出(java.lang.OutOfMemoryError)的常见情况和处理方式总结(转)
    Android java.net.SocketException四大异常解决方案
    Android 设定activity的进入和退出效果
    Android TabHost 动态修改图标或者动态改变标题
    Android TabHost中实现标签的滚动以及一些TabHost开发的奇怪问题
    Android 动态Tab分页效果
    Android ActionBar通过Tab进行不同的Fragment之间的交换
    Android 如何动态改变Actionbar上的item图标
    RGB颜色查询对照表
  • 原文地址:https://www.cnblogs.com/UncleWang001/p/10794393.html
Copyright © 2011-2022 走看看