Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在方法仍然完成时发送HTTP Ok请求?_Java_Spring_Multithreading_Http_Asynchronous - Fatal编程技术网

Java 如何在方法仍然完成时发送HTTP Ok请求?

Java 如何在方法仍然完成时发送HTTP Ok请求?,java,spring,multithreading,http,asynchronous,Java,Spring,Multithreading,Http,Asynchronous,我还是多线程新手,不知道如何实现。我有一个Spring应用程序,当它被调用时,我希望能够从控制器发送OK状态,比如从Postman,而在它中调用的方法仍然在后台完成。我可以问一下示例代码如何做到这一点吗?下面是我想使之异步的方法: public void methodForAsynchronousTask(){ restTemplate.exchange(url, method, requestEntity, String.class); } 这是我的控制器: @PostMapping

我还是多线程新手,不知道如何实现。我有一个Spring应用程序,当它被调用时,我希望能够从控制器发送OK状态,比如从Postman,而在它中调用的方法仍然在后台完成。我可以问一下示例代码如何做到这一点吗?下面是我想使之异步的方法:

public void methodForAsynchronousTask(){
    restTemplate.exchange(url, method, requestEntity, String.class);
}
这是我的控制器:

@PostMapping("/")
public ResponseEntity<?> startOutage() {
    someClass.methodForAsynchronousTask();
    return new ResponseEntity<>(HttpStatus.OK);
}
@PostMapping(“/”)
公众反应startOutage(){
someClass.MethodforSynchronousTask();
返回新的响应状态(HttpStatus.OK);
}

我会在
someClass
实现中使用
ExecutorService
,限制创建的线程数:

@Component
public class SomeClass {
  
  private ExecutorService executorService;
  private RestTemplate restTemplate;
  
  public SomeClass() {
    this.executorService = Executors.newFixedThreadPool(10);
    this.restTemplate = new RestTemplateBuilder().build();
  }  

  public someMethodForAsynchronousTask() {
    executorService.submit( () -> {
      restTemplate.exchange(url, method, requestEntity, String.class);
      .. // and whatever else
    });
  }
}

这回答了你的问题吗?感谢您的建议@christianfoleide,它很有效,是一个非常优雅的解决方案