验证某事不正确的最简单方法是定义一个超时值,然后在循环测试期间,如果您花费的等待时间超过了超时。
类似:
@Controller
public class MyController
{
private static final long MAX_LOOP_TIME = 1000 * 60 * 5; // 5 minutes? choose a value
@RequestMapping(value="/do", method=RequestMethod.GET)
public String do()
{
File f = new File("otherMethodEnded.tmp");
long startedAt = System.currentTimeMillis()
boolean forcedExit = false;
while (!forcedExit && !f.exists())
{
try {
Thread.sleep(5000);
if (System.currentTimeMillis() - startedAt > MAX_LOOP_TIME) {
forcedExit = true;
}
} catch (InterruptedException e) {
forcedExit = true;
}
}
// ok, let's continue
// if forcedExit , handle error scenario?
}
}
另外:InterruptedException 不是盲目捕捉和忽略的东西。见this discussion
如果你被打断,我真的会退出 while 循环。
只有当您注意到您写入的输出流 (response.outputstream) 已关闭时,您才知道客户端是否不再等待您的连接。但是没有办法检测它。
(详见this question)
鉴于您已表明您的客户偶尔会进行回调,您可以在客户端轮询其他呼叫是否已完成。如果此其他调用已完成,则执行该操作,否则直接返回并让客户端再次执行该调用。 (假设您正在发送 json,但根据需要进行调整)
类似
public class MyController
{
@RequestMapping(value="/do", method=RequestMethod.GET)
public String do()
{
File f = new File("otherMethodEnded.tmp");
if (f.exists()) {
// do what you set out to do
// ok, let's continue
// and return with a response that indicates the call did what it did
// view that returns json { "result" : "success" }
return "viewThatSIgnalsToClientThatOperationSucceeded";
} else {
// view that returns json: { "result" : "retry" }
return "viewThatSignalsToClientToRetryIn5Seconds";
}
}
}
然后客户端会运行类似:(伪javascript,因为它已经有一段时间了)
val callinterval = setInterval(function() { checkServer() }, 5000);
function checkServer() {
$.ajax({
// ...
success: successFunction
});
}
function successFunction(response) {
// connection succeeded
var json = $.parseJSON(response);
if (json.result === "retry") {
// interval will call this again
} else {
clearInterval(callinterval);
if (json.result === "success") {
// do the good stuff
} else if (json.result === "failure") {
// report that the server reported an error
}
}
}
当然,这只是半严肃的代码,但如果我有依赖关系,这大致就是我尝试的方式。如果这是关于文件上传,请记住该文件可能尚未包含所有字节。文件存在!= 文件= 完全上传,除非您使用移动它。 cp / scp / etc. 不是原子的。