[英]How to invoke async controller logic after returning response using Spring?
I need to process request asynchronously in time - after receiving request I must return a response with status 200 to confirm that the request have reached it's goal, and then proceed with some magic to happen in service. 我需要及时异步处理请求 - 在收到请求后,我必须返回状态为200的响应,以确认请求已达到目标,然后继续在服务中发生一些魔术。 I tried few ways to reach it, but every time response was sent after logic part ended in some other thread.
我尝试了几种方法来达到它,但每次响应都是在逻辑部分以其他线程结束后发送的。
Is there a way to reach it using Spring? 有没有办法使用Spring达到它? Or should I rather think about other approach to this problem?
或者我应该考虑其他方法来解决这个问题?
The Spring Framework provides abstractions for asynchronous execution and scheduling of tasks
Spring Framework提供了异步执行和任务调度的抽象
You can look at this => http://docs.spring.io/spring/docs/current/spring-framework-reference/html/scheduling.html 你可以看看这个=> http://docs.spring.io/spring/docs/current/spring-framework-reference/html/scheduling.html
You need to use deferredResult http://docs.spring.io/spring-framework/docs/3.2.0.BUILD-SNAPSHOT/api/org/springframework/web/context/request/async/DeferredResult.html 你需要使用deferredResult http://docs.spring.io/spring-framework/docs/3.2.0.BUILD-SNAPSHOT/api/org/springframework/web/context/request/async/DeferredResult.html
You will create a deferredResult object and you will return to the client. 您将创建一个deferredResult对象,然后您将返回到客户端。 then asynchronously you will execute the logic and as soon as you finish you will inform the client that the request it´s done.
然后异步您将执行逻辑,一旦完成,您将通知客户端请求已完成。 This technique is also know as "http long polling"
这种技术也被称为“http长轮询”
@RequestMapping("/")
@ResponseBody
public DeferredResult<String> square() throws JMSException {
final DeferredResult<String> deferredResult = new DeferredResult<>();
runInOtherThread(deferredResult);
return deferredResult;
}
private void runInOtherThread(DeferredResult<String> deferredResult) {
//seconds later in other thread...
deferredResult.setResult("HTTP response is: 42");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.