2011-04-15 45 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