假设我使用POSTMAN在带有localhost:8080/admin/hello
类POST JSON对象的URI Hello
上单击,并且有一个类似Controller,
@RequestMapping(value = "/hello", method = RequestMethod.POST)
public ResponseEntity<Hello> helloHome(@RequestBody Hello obj){
//here it goes to service class and doing processes...
return new ResponseEntity<Hello>(obj, HttpStatus.OK);
}
我只希望URI到达Controller,但不等待响应(因为处理所有服务类过程需要10秒钟,但我想立即返回而没有响应)。
我该如何实施?
答案 0 :(得分:3)
将所有处理逻辑移到Service类(如果还没有),并用@Async
注释您的Service类方法。这将使方法调用在单独的线程中执行,并且控制器方法将不等待服务类方法完成。
@RequestMapping(value = "/hello", method = RequestMethod.POST)
public ResponseEntity<Hello> helloHome(@RequestBody Hello obj){
helloHomeService.processRequest(obj);
return new ResponseEntity<Hello>(obj, HttpStatus.OK);
}
public Class HomeService{
@Async
public void processRequest(Hello obj){
//processing logic
}
}
答案 1 :(得分:1)
您可以使用@EnableAsync启用Async:
@Configuration
@EnableAsync
class AsyncConfig{}
@Component //in order to be scanned
class YourService{
@Async
public void asyncMethod(args){}
}
}
in your controller:
@Autowired
private YourService service;
....
public ResponseEntity<Hello> helloHome(@RequestBody Hello obj){
service.asyncMethode(params);
return new ResponseEntity<Hello>(obj, HttpStatus.OK);
}
答案 2 :(得分:1)
您可以通过配置启用异步处理。
@Configuration
@EnableAsync
public class YourConfig
现在,您可以添加服务并通过用@Async
对其进行注释来启用异步处理。它将在调用后立即返回。
@Async
public void asyncMethodOnAService() {}
如果您要返回一个值,则可以返回CompletableFuture
@Async
public CompletableFuture<String> asyncMethodOnAService() {}
调用async方法的控制器可以返回DeferredResult
,这将使客户端知道一旦异步处理完成,结果将可用。
@RequestMapping(value = "/async", method = RequestMethod.GET)
public DeferredResult<ResponseEntity<String>> doAsync() {
DeferredResult<ResponseEntity<String>> result = new DeferredResult<>();
this.asyncService.asyncMethodOnAService().whenComplete((serviceResult, throwable) -> result.setResult(ResponseEntity.ok(serviceResult)));
return result;
}