2011-04-15 80 views
1

我必須以5 tps的速率對外部服務器進行網絡呼叫。每個網絡呼叫通常需要大約7秒才能完成。我如何實現這一點。你會爲此推薦PHP嗎?進行大量的網絡呼叫

回答

2

這是Java解決方案,因爲您用Java標記了問題。它會每秒向網站發出5次請求。由於您表示這些請求可能需要很長時間,因此一次最多可以使用50個線程以避免被阻止。

final URL url = new URL("http://whitefang34.com"); 
Runnable runnable = new Runnable() { 
    public void run() { 
     try { 
      InputStream in = url.openStream(); 
      // process input 
      in.close(); 
     } catch (IOException e) { 
      // deal with exception 
     } 
    } 
}; 

ExecutorService service = Executors.newFixedThreadPool(50); 
long nextTime = System.currentTimeMillis(); 
while (true) { 
    service.submit(runnable); 
    long waitTime = nextTime - System.currentTimeMillis(); 
    Thread.sleep(Math.max(0, waitTime)); 
    nextTime += 200; 
} 
+0

這是否會並行執行調用?從這個問題來看,他們需要的時間比他們之間的時間差。 – 2011-04-15 10:23:34

+0

是的,它會並行執行多達50個。 – WhiteFang34 2011-04-15 10:25:05

+0

我想你的意思是'scheduleAtFixedRate' – 2011-04-15 10:25:17