客户端如何处理长时间运行的休息调用中的延迟结果

时间:2016-12-24 20:42:47

标签: java spring rest nonblocking

我正在学习spring mvc / boot。我理解基本的休息呼叫,但我无法理解长时间运行/非阻塞休息呼叫。

据我所知,对于长时间运行的休息调用,我们启动一个单独的线程,服务器将DeferredResult对象返回给客户端,但是当处理线程完成时如何通知客户端?

有人能为我提供一个如何在客户端处理此问题的示例吗?

非java客户端如何处理此类请求?

2 个答案:

答案 0 :(得分:1)

我给出了与Spring相关的答案,与任何非Java客户端无关。

AsyncRestTemplate可用于从长时间运行的Rest Webservice中检索

http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/client/AsyncRestTemplate.html

// WAY1

    @Test
    public void testGetClusterAsyncWay1() 
    {
        Future<ResponseEntity<ClusterDTO>> future =  asyncRestTemplate.getForEntity(BASE_URI+"/async/{clusterId}", ClusterDTO.class,1);

        //Do some other work in your method and after that ping the service to retrieve the result

        //Waits for the computation to get complete and then get the result , you can use different version of get which has timeout option
        ResponseEntity<ClusterDTO> response = future.get();

        ClusterDTO cluster = response.getBody();

        System.out.println("testGetClusterAsync()"+cluster.getClusterName());

}

// WAY2

    @Test
    public void testGetClusterAsyncWay2() 
    {

          ListenableFuture<ResponseEntity<ClusterDTO>> future = 
                    asyncRestTemplate.getForEntity(BASE_URI+"/async/{clusterId}", ClusterDTO.class,17);

       future.addCallback(new MyCallbackHandler());

        //do stuff
        for(int i=0;i<10000;i++)
        {

            System.out.println(i);
        }

    }
    class MyCallbackHandler implements  ListenableFutureCallback<ResponseEntity<ClusterDTO>>{

    @Override
     public void onSuccess(ResponseEntity<ClusterDTO> response) {
      ClusterDTO cluster = response.getBody();
      System.out.println(cluster);
      System.out.println("Success******************************");
     }

    @Override
    public void onFailure(Throwable ex) {
    System.out.println("onFailure******************************");
    ex.printStackTrace();

    }

}

答案 1 :(得分:0)

Web不是为长时间运行的任务而构建的,它纯粹是请求/响应。但是,您可以使用Server Sent Events将通知返回给客户端或使用Websockets。 Spring支持两者。

https://github.com/cedricziel/demo-sse-spring-boot

https://spring.io/guides/gs/messaging-stomp-websocket/