实例:接口并发限流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 中获取令牌。成功择执行,失败则阻塞 直到拿到令牌才继续执行

上一篇:Windows Azure 安全最佳实践 - 第 2 部分:Azure 提供哪些现成可用的安全机制


下一篇:[转]Android开发最佳实践