我想从给定的网址获取所有网址,我想查看每个网址的状态。
为此,我使用ExecutorService
进行多线程检查每个网址的状态。
检查网址响应代码的类代码如下所示
public class ConnectionTester implements Callable<Object> {
private URL url;
private Map<String,Integer> map;
private static final Log LOGGER =
LogFactoryUtil.getLog(ConnectionTester.class);
public ConnectionTester(String url,Map<String,Integer> map) {
try {
this.url = new URL(url);
this.map = map;
} catch (MalformedURLException e) {
LOGGER.error(e.getMessage(), e);
}
}
/**
* Get status code of url
* @return
*/
public void getStatuscode(URL url) {
HttpURLConnection http = null;
try {
http = (HttpURLConnection)url.openConnection();
http.setConnectTimeout(0);
http.setReadTimeout(0);
http.setRequestMethod("HEAD");
http.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 10.0;
Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/56.0.2924.87 Safari/537.36");
http.connect();
map.put(url.toString(), http.getResponseCode());
} catch (IOException e) {
map.put(url.toString(), 500 );
}finally{
if(http !=null)http.disconnect();
}
}
@Override
public Object call() throws Exception {
getStatuscode(url);
return null;
}
}
我使用以下代码检查每个网址的响应代码
ExecutorService service = Executors.newFixedThreadPool(urls.size());
List<ConnectionTester> connectionTesters = new ArrayList<ConnectionTester>(urls.size());
Map<String,Integer> map = new HashMap<String, Integer>();
for (String string : urls) {
if(Validator.isNotNull(string) && !string.contains("mailto"))
connectionTesters.add(new ConnectionTester(string, map));
}
service.invokeAll(connectionTesters);
现在的问题是,当我不使用多线程时,我得到了每个URL的正确响应代码,但是当我使用多线程时,我收到连接超时异常。
到目前为止,我已经检查并尝试过以下内容。
http.setConnectTimeout(0); http.setReadTimeout(0);
设置为无限时间。我在这里缺少什么?
答案 0 :(得分:1)
您正在超载服务器。当Unix / Linux TCP服务器的 listen(2)积压队列填满时,它会开始忽略传入的连接请求,这会导致客户端的连接超时。
解决方案:不要。减少线程数,当线程获得连接超时时,不要再创建。