异步弹簧控制器 - 处理未来结果

时间:2016-02-01 22:50:45

标签: spring spring-mvc

我是未来的新手,我正在试图弄清楚如何在这个场景中处理可听的未来:

@Controller
@EnableAutoConfiguration
public class ListenableFutureAsyncController {

    @Autowired
    IHeavyLiftingService heavyLiftingService;

    @RequestMapping("/")
    @ResponseBody
    DeferredResult<String> home() {
        // Create DeferredResult
        final DeferredResult<String> result = new DeferredResult<>();

        //Call to the async service
        ListenableFuture<ResponseEntity<String>> future = heavyLiftingService.heavyLifting();

        future.addCallback(
          new ListenableFutureCallback<ResponseEntity<String>>() {
            @Override
            public void onSuccess(ResponseEntity<String> response) {
                result.setResult(response.getBody());
            }

            @Override
            public void onFailure(Throwable t) {
                result.setErrorResult(t.getMessage());
            }
        });
        // Return the thread to servlet container, 
        // the response will be processed by another thread.
        return result;
    }

}

除了将其传递回控制器之外,我如何处理未来。防爆。如果我想将未来的字符串保存到数据库怎么办?

@Service
public class HeavyLiftingServiceImpl implements IHeavyLiftingService {

    public ListenableFuture<String> heavyLifting() {
        AsyncRestTemplate asycTemp = new AsyncRestTemplate();
        ListenableFuture<String> future = asycTemp.execute(url, method, requestCallback, responseExtractor, urlVariable);
        /** 
        /Save future string to db
        **/
        return future;
    }
}

1 个答案:

答案 0 :(得分:2)

我已经找到了使用Spring ListenableFutureAdapter

执行此操作的方法
@Service
public class HeavyLiftingServiceImpl implements IHeavyLiftingService {

    public ListenableFuture<String> heavyLifting() {
        AsyncRestTemplate asycTemp = new AsyncRestTemplate();
        ListenableFuture<String> future = asycTemp.execute(url, method, requestCallback, responseExtractor, urlVariable);

        ListenableFutureAdapter<String, String> chainedFuture;
        chainedFuture = new ListenableFutureAdapter<String, String>(future) {

            @Override
            protected String adapt(String adapteeResult)
                    throws ExecutionException {
                        String parsedString = parse(adapteeResult);
                        return adapteeResult;
            }
        };

        return chainedFuture;
    }

}

我建议使用Guava实现可听的未来。我发现它更具可读性,将链接在一起的文档更容易找到。