1.说明
都是网上拿过来的,记录一下,总结一下。
2.可以这么理解,但不建议这么做
有就获取,没有就keepPolling
@Notice(comment = "保持轮询")
private ResponseEntity<List<CustomMessage>> keepPolling(GetMessage input) throws InterruptedException {
Thread.sleep(5000);
HttpHeaders headers = new HttpHeaders();
headers.setLocation(URI.create("/getMessages?id=" + input.getId() + "&to=" + input.getTo()));
return new ResponseEntity<>(headers, HttpStatus.TEMPORARY_REDIRECT);
}
3.建议这么做
前端
var loopCall = function() {
$.get("${yourContext}/call", function(r) {
loopCall();
console.log("call: ");
console.log(r);
});
};
loopCall(); // 循环发起异步请求
后端
@RequestMapping
@Controller
public class CallController {
@Autowired
private DeferredResultHolder deferredResultHolder;
@RequestMapping("/call")
@ResponseBody
public DeferredResult<DeferredData> call() {
String id = "abc";
return deferredResultHolder.newDeferredResult(id, 10 * 1000L, null);
}
}
demo
@RequestMapping("/call")
@ResponseBody
public DeferredResult<Object> call() { // 泛型Object表示返回结果的类型
DeferredResult<Object> response = new DeferredResult<Object>(
10000L, // 请求的超时时间
null); // 超时后响应的结果
response.onCompletion(new Runnable() {
@Override
public void run() {
// 请求处理完成后所做的一些工作
}
});
// 设置响应结果
// 调用此方法时立即向浏览器发出响应;未调用时请求被挂起
response.setResult(new Object());
return response;
}