某個接口有訪問頻率限制,限制一分鐘最多能夠訪問XX次,在訪問代碼中增長限流器,以下 java
// 限制每分鐘訪問次數 int tpm = SystemConfigs.getInt(SysConfigKeys.XXX_TPM); int count = 0, round = 0; List<XXX> list = new ArrayList<XXX>(); long startMillis = System.currentTimeMillis(); while (start.before(end)) {//按時間段不停的訪問接口 // 預計時間開銷 long predict = round * 60000 / tpm; long duration = System.currentTimeMillis() - startMillis; if(predict > duration) { // 實際耗時小於預計耗時,sleep long waitting = predict - duration; try { Thread.sleep(waitting); LOG.debug("XXX同步休眠{}ms. ", waitting); } catch (InterruptedException e) { LOG.error("XXX訪問頻率限制失敗:", e); } } round ++; count += this.syncData(start); start = DateUtils.addDay(start, 1); } LOG.info("總共同步了{}條數據!", count); return "XXX同步了" + count + "條數據!";