spring无阻塞休息“发送并忘记”
问题内容:
我正在编写一个非阻塞的Spring Rest控制器。我的客户应该发送请求,并且不关心响应,也不需要等待。
这是我的服务器代码:
@RestController
@EnableAsync
public class testController {
@RequestMapping(value = "test", method = RequestMethod.GET)
public ResponseEntity<String> test() throws InterruptedException {
timeConsumingMethod();
System.out.println("I'm should be first");
return new ResponseEntity<String>("the server is processing your request", HttpStatus.OK);
}
@Async
private void timeConsumingMethod() throws InterruptedException {
Thread.sleep(1000*5);
System.out.println("I'm should be second!");
}
但是,当我使用(POSTMAN,Chrome等…)调用http:// localhost:8181 /
test
时,服务器日志上显示以下内容:
我应该是第二!
我应该先
并且仅在等待5秒后,我的浏览器显示:
服务器正在处理您的请求
这是“发送并忘记”行为的正确方法吗?
问题答案:
根据文档页面,@EnableAsync
应将其添加到配置类中。
启用Spring的异步方法执行功能,类似于Spring的XML名称空间中的功能。
要在@Configuration类上使用,如下所示,其中MyAsyncBean是用户定义的类型,具有一个或多个方法,这些方法用Spring的@Async批注,EJB
3.1 @ javax.ejb.Asynchronous批注或通过该批注指定的任何自定义批注进行批注。 ()属性。