1. 程式人生 > >springmvc DeferredResult處理異步請求

springmvc DeferredResult處理異步請求

return std 隊列 jms cti another roc tde amp

DeferredResult

使用場景:類似於Callable,但相比於Callable使用更復雜的業務情況:對於一次請求,其處理結果可能是其它系統(線程)才能處理的,

在其它系統(線程)未將結果處理完放進DeferredResult中之前一直阻塞

A controller method can also return a DeferredResult (new type in Spring MVC 3.2) to complete processing in a thread not known to Spring MVC. For example reacting to a JMS or an AMQP message, a Redis notification, and so on. Here is another code snippet

示例:

@RequestMapping("/front/test_DeferredResult")
    public DeferredResult<String> testDefer() {
        //3000L超時時間,time out超時說明
        DeferredResult<String> deferredResult = new DeferredResult<String>(3000L,"time out");
        // 在其它線程給deferredResult設置處理結果後會返回給客戶端
        // 模擬隊列
        SampleQueen.add(deferredResult);
        return deferredResult;
    }
    @RequestMapping("/front/set_DeferredResult")
    public String setResult2DeferredResult() {
        DeferredResult<String> deferredResult = SampleQueen.get();
        //模擬隊列將處理結果放回
        deferredResult.setResult("test success");
        return "set test success";
    }

  在訪問/front/test_DeferredResult時會在超時範圍內等待

在模擬其他消息處理的請求/front/set_DeferredResult將結果放回DeferredResult後,/front/test_DeferredResult會得到響應。

springmvc DeferredResult處理異步請求