我们使用以下Apache Commons Net FTP代码连接到FTP服务器,轮询某些目录中的文件,如果找到文件,则将它们检索到本地计算机:
try {
logger.trace("Attempting to connect to server...");
// Connect to server
FTPClient ftpClient = new FTPClient();
ftpClient.setConnectTimeout(20000);
ftpClient.connect("my-server-host-name");
ftpClient.login("myUser", "myPswd");
ftpClient.changeWorkingDirectory("/loadables/");
// Check for failed connection
if(!FTPReply.isPositiveCompletion(ftpClient.getReplyCode()))
{
ftpClient.disconnect();
throw new FTPConnectionClosedException("Unable to connect to FTP server.");
}
// Log success msg
logger.trace("...connection was successful.");
// Change to the loadables/ directory where we poll for files
ftpClient.changeWorkingDirectory("/loadables/");
// Indicate we're about to poll
logger.trace("About to check loadables/ for files...");
// Poll for files.
FTPFile[] filesList = oFTP.listFiles();
for(FTPFile tmpFile : filesList)
{
if(tmpFile.isDirectory())
continue;
FileOutputStream fileOut = new FileOutputStream(new File("tmp"));
ftpClient.retrieveFile(tmpFile.getName(), fileOut);
// ... Doing a bunch of things with output stream
// to copy the contents of the file down to the local
// machine. Ommitted for brevity but I assure you this
// works (except when the WAR decides to hang).
//
// This was used because FTPClient doesn't appear to GET
// whole copies of the files, only FTPFiles which seem like
// file metadata...
}
// Indicate file fetch completed.
logger.trace("File fetch completed.");
// Disconnect and finish.
if(ftpClient.isConnected())
ftpClient.disconnect();
logger.trace("Poll completed.");
} catch(Throwable t) {
logger.trace("Error: " + t.getMessage());
}
我们计划将其每分钟运行一次。当部署到Tomcat(7.0.19)时,此代码可以很好地加载并开始正常运行。但是,每次似乎都在挂起。我的意思是:
catalina.out
我的应用程序专用日志没有任何异常抛出的迹象因此,JVM仍在运行。Tomcat仍在运行,而我部署的WAR仍在运行,但是它刚刚挂起。有时它会运行2个小时,然后挂起。有时它会运行几天然后挂起。但是,当它挂起时,它会在读取的行About to check loadables/ for files...
(我确实在日志中看到)和读取的行File fetch completed.
(我未看到)之间这样做。
这告诉我挂起发生在实际轮询/获取文件的过程中,这使我指出了与该问题相同的方向,这一问题使我能够找到与FTPClient死锁有关的问题。这让我想知道这些是否是相同的问题(如果是,我将很乐意删除此问题!)。不过,我不认为认为它们是相同的(我没有看到我日志中的同样的例外)。
一位同事提到这可能是“被动”与“主动” FTP的问题。没有真正知道的区别,我由FTPClient领域糊涂一点ACTIVE_REMOTE_DATA_CONNECTION_MODE
,PASSIVE_REMOTE_DATA_CONNECTION_MODE
等等,不知道为什么情绪这么想过,作为一个潜在的问题。
由于我在Throwable
这里是不得已而为之的方法,因此,如果出现问题,我本可以期望在日志中看到某些内容。嗯,我觉得这绝对是个难题。
有任何想法吗?不幸的是,我对FTP的内部知识了解不足,无法做出可靠的诊断。这可能是服务器端的东西吗?与FTP服务器相关?
这可能有很多事情,但是您朋友的建议是值得的。
尝试ftpClient.enterLocalPassiveMode();
看看是否有帮助。
我还建议将断开连接放在finally
块中,以使其永远不会留下连接。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句