我必须以5 tps的速率向外部服务器进行Web调用。每次网络通话通常需要大约7秒才能完成。我该如何实现呢。你会推荐PHP吗?
答案 0 :(得分: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;
}