【问题标题】:How to build a Non Blocking Asynchronous Web service Using Spring boot如何使用 Spring Boot 构建非阻塞异步 Web 服务
【发布时间】:2017-11-12 14:23:28
【问题描述】:
【问题讨论】:
标签:
java
asynchronous
spring-boot
nonblocking
【解决方案1】:
Spring Boot 自动支持Servlet spec 3+ async handling of http 请求。
最简单的利用方式如下:
public Callable<ResponseEntity<?>> myProcessingMethod () {
return () -> ResponseEntity.ok (myHeavyService.doTheWork ());
}
上面的重点是尽快释放你的HTTP请求处理线程,以便为下一个请求做好准备。
服务调用完成后,控制权将返回到 http 处理线程,以便将结果发送给调用者。
现在,如果您希望服务方法异步执行,您可以使用 @Async 注释该方法。
但是,您不能在上面的休息处理程序中使用该方法。
上面的代码需要改成这样的:
public ResponseEntity<?> myProcessingMethod () {
myHeavyService.doTheWorkAsync ()
return ResponseEntity.ok ();
}
【解决方案3】:
Public interface Callback<T>{
public void callWhenDone(T result);
//process the result in you implemenation
}
启动处理数据库查询的线程
public class MyThread implements Runnable {
Callback callback;
//create thread by passing implemenation of callback
public MyThread(Object parameter,Callback c) {
// store parameter for later user
this.callback=c;
}
public void run() {
//call db queries and when you get the results call the callbak
callback.callWhenDone(result);
}
}
启动线程 new MyThread(params,CallBackImplemntation).start()