2017-02-24 45 views
0

我必須在Spark API實現中調用長時間運行的方法。這些方法返回CompletableFutures,所以我想通過觸發Spark在回調中回答客戶端請求來釋放當前的線程。 據我可以告訴這是不可能與Spark,但我想確保我不俯瞰任何東西。 爲了說明這個問題,請參閱下面的小代碼示例。Java Spark:CompletableFutures的非阻塞路由/回調

import spark.Spark; 
import java.util.concurrent.CompletableFuture; 

public class HelloSpark { 

    public static void main(String[] args) { 
     Spark.get("/what_i_have_to_do", (req, res) -> { 
      CompletableFuture<String> f = callToSlowWorker(); 
      return f.get(); 
     }); 

     Spark.get("/what_i_would_like_to_do", (req, res) -> { 
      CompletableFuture<String> f = callToSlowWorker(); 
      f.whenComplete((answer, throwable) -> { 
       if(throwable != null){ 
        // send error to requesting client 
        res.status(500); 
        res.body(throwable.getMessage()); 
       } else { 
        // send answer to requesting client 
        res.body(answer); 
       } 
       // trigger spark to return the response to the client 
       // ...?!? 
      }); 
      return null; // obviously not what I want, just to make this sample code compile 
     }); 
    } 

    static CompletableFuture<String> callToSlowWorker(){ 
     return CompletableFuture.supplyAsync(() -> { 
      try { 
       Thread.sleep(1000); 
      } catch (InterruptedException ignored) { 
      } 
      return "Hello World"; 
     }); 
    } 
} 

回答

1

SparkJava目前只能阻塞,因此你所描述的是不可能的。有一個開放的enhancement request來添加對非阻塞API的支持。