主要目标是通过REST服务将xml文件从一个文件夹发送到Cassandra数据库。我想做的就是读取特定文件夹中的所有文件,并创建一个Worker对象,其中设置了文件路径。
while (RUNS > 0) {
ExecutorService executor = Executors.newFixedThreadPool(N_THREADS);
File dir = new File(PATH_TO_SAMPLES);
File[] listFiles = dir.listFiles();
if (listFiles != null) {
for (File file : listFiles) {
Worker worker = new Worker();
worker.setPath(file.toPath());
executor.submit(worker);
}
}
executor.shutdown();
// Wait until all threads are finish
while (!executor.isTerminated()) {
}
Thread.sleep(1000);
RUNS--;
}
在此之后,执行器获取一个工作实例并转到目录中的下一个文件。 RUNS初始化为迭代的总数,默认值为100_000。 N_THREADS - 线程的总数,默认设置为100。
Worker类实现了Runnable接口。Run方法:
@Override
public void run() {
String url = getUrl();
String payload = "xml_file_representation";
MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
HttpClient client = new HttpClient();
HttpConnectionManagerParams httpConnectionManagerParams = new HttpConnectionManagerParams();
connectionManager.setParams(httpConnectionManagerParams);
client.setHttpConnectionManager(connectionManager);
PostMethod postMethod = new PostMethod(url);
try {
postMethod.setRequestHeader("User-Agent", USER_AGENT);
postMethod.setRequestHeader("Content-Type", "application/xml");
postMethod.setRequestEntity(new StringRequestEntity(payload, "application/xml", StandardCharsets.UTF_8.toString()));
int statusCode = client.executeMethod(postMethod);
InputStream body = postMethod.getResponseBodyAsStream();
if (statusCode == HttpStatus.SC_OK) {
//OK
}
} catch (Exception e) {
LOG.error("POST: ERROR!");
} finally {
postMethod.releaseConnection();
connectionManager.shutdown();
}
}
如果我删除等待,即在run结束时删除Thread.sleep(1000);,当发送了约16_000个请求时,我会收到一个异常:
java.net.BindException: Address already in use
这与客户端套接字上的BindException:地址已在使用中非常相似。
无论如何,被接受的答案对我没有帮助。我不知道该怎么做才能关闭那些“连接”,以防止出现该错误。
像Thread.sleep()这样的解决方法也不是一个好的解决方案。感谢任何帮助或建议。