成人国产在线小视频_日韩寡妇人妻调教在线播放_色成人www永久在线观看_2018国产精品久久_亚洲欧美高清在线30p_亚洲少妇综合一区_黄色在线播放国产_亚洲另类技巧小说校园_国产主播xx日韩_a级毛片在线免费

資訊專欄INFORMATION COLUMN

Spring MVC異步處理簡介

Sike / 1784人閱讀

摘要:異步處理簡介地址相關(guān)系列文章異步處理詳解分析本文講到的所有特性皆是基于的,不是基于的。用于異步返回結(jié)果,使用自己的,使用負(fù)責(zé)處理它。配置執(zhí)行異步操作需要用到,這個(gè)可以在用方法來提供相關(guān)文檔。

Spring MVC異步處理簡介

Github地址

相關(guān)系列文章:

Servlet 3.0 異步處理詳解

Servlet 3.1 Async IO分析

本文講到的所有特性皆是基于Servlet 3.0 Async Processing的,不是基于Servlet 3.1 Async IO的。

Callable
A Callable can be returned when the application wants to produce the return value asynchronously in a thread managed by Spring MVC.

用于異步返回結(jié)果,使用的是Spring MVC的AsyncTaskExecutor,Spring MVC使用CallableMethodReturnValueHandler負(fù)責(zé)處理它。

下面是例子CallableController:

@RestController
public class CallableController {

  @RequestMapping("callable-hello")
  public Callable hello() {
    return () -> new SlowJob("CallableController").doWork();
  }
}

用瀏覽器訪問:http://localhost:8080/callable-hello 查看返回結(jié)果。

DeferredResult
A DeferredResult can be returned when the application wants to produce the return value from a thread of its own choosing.

用于異步返回結(jié)果,使用的是client code自己的thread,Spring MVC使用DeferredResultMethodReturnValueHandler負(fù)責(zé)處理它。

下面是例子DeferredResultController:

@RestController
public class DeferredResultController {

  @Autowired
  @Qualifier("customExecutorService")
  private ExecutorService executorService;

  @RequestMapping("deferred-result-hello")
  public DeferredResult hello() {
    DeferredResult deferredResult = new DeferredResult<>();
    executorService.submit(() -> {
      try {
        deferredResult.setResult(new SlowJob("DeferredResultController").doWork());
      } catch (Exception e) {
        deferredResult.setErrorResult(e);
      }

    });
    return deferredResult;
  }

}

在這個(gè)例子里使用了ExecutorService(見ExecutorServiceConfiguration),你也可以根據(jù)實(shí)際情況采用別的機(jī)制來給DeferredResult.setResult

用瀏覽器訪問:http://localhost:8080/deferred-result-hello 查看返回結(jié)果。

ListenableFuture or CompletableFuture/CompletionStage
A ListenableFuture or CompletableFuture/CompletionStage can be returned when the application wants to produce the value from a thread pool submission.

用于異步返回結(jié)果,使用client code自己的thread pool,Spring MVC使用DeferredResultMethodReturnValueHandler負(fù)責(zé)處理它。

下面是例子ListenableFutureController:

@RestController
public class ListenableFutureController {

  @Autowired
  @Qualifier("customExecutorService")
  private ExecutorService executorService;

  @RequestMapping("listenable-future-hello")
  public ListenableFutureTask hello() {

    ListenableFutureTask listenableFutureTask = new ListenableFutureTask<>(
        () -> new SlowJob("ListenableFutureController").doWork());
    executorService.submit(listenableFutureTask);
    return listenableFutureTask;
  }

}

用瀏覽器訪問:http://localhost:8080/listenable-future-hello 查看返回結(jié)果。

下面是例子CompletionFutureController

@RestController
public class CompletionFutureController {

  @RequestMapping("completable-future-hello")
  public CompletableFuture hello() {

    return CompletableFuture
        .supplyAsync(() -> new SlowJob("CompletionFutureController").doWork());
  }

}

用瀏覽器訪問:http://localhost:8080/completable-future-hello 查看返回結(jié)果。

ResponseBodyEmitter
A ResponseBodyEmitter can be returned to write multiple objects to the response asynchronously; also supported as the body within a ResponseEntity.

用于異步的寫入多個(gè)消息,使用的是client code自己的thread,Spring MVC使用ResponseBodyEmitterReturnValueHandler負(fù)責(zé)處理它。

下面是例子ResponseBodyEmitterController

@RestController
public class ResponseBodyEmitterController {

  @Autowired
  @Qualifier("customExecutorService")
  private ExecutorService executorService;

  @RequestMapping("response-body-emitter-hello")
  public ResponseBodyEmitter hello() {

    ResponseBodyEmitter emitter = new ResponseBodyEmitter();
    executorService.submit(() -> {
      try {
        for (int i = 0; i < 5; i++) {

          String hello = new SlowJob("ResponseBodyEmitterController").doWork();
          emitter.send("Count: " + (i + 1));
          emitter.send("
");
          emitter.send(hello);
          emitter.send("

");
        }
        emitter.complete();
      } catch (Exception e) {
        emitter.completeWithError(e);
      }

    });

    return emitter;
  }
}

用瀏覽器訪問:http://localhost:8080/response-body-emitter-hello 查看返回結(jié)果。

SseEmitter
An SseEmitter can be returned to write Server-Sent Events to the response asynchronously; also supported as the body within a ResponseEntity.

作用和ResponseBodyEmitter類似,也是異步的寫入多個(gè)消息,使用的是client code自己的thread,區(qū)別在于它使用的是Server-Sent Events。Spring MVC使用ResponseBodyEmitterReturnValueHandler負(fù)責(zé)處理它。

下面是例子SseEmitterController

@RestController
public class SseEmitterController {

  @Autowired
  @Qualifier("customExecutorService")
  private ExecutorService executorService;

  @RequestMapping("sse-emitter-hello")
  public ResponseBodyEmitter hello() {

    SseEmitter emitter = new SseEmitter();
    executorService.submit(() -> {
      try {
        for (int i = 0; i < 5; i++) {

          String hello = new SlowJob("SseEmitterController").doWork();
          StringBuilder sb = new StringBuilder();
          sb.append("Count: " + (i + 1)).append(". ").append(hello.replace("
", ""));
          emitter.send(sb.toString());
        }
        emitter.complete();
      } catch (Exception e) {
        emitter.completeWithError(e);
      }

    });

    return emitter;
  }
}

用瀏覽器訪問:http://localhost:8080/sse-emitter-hello 查看返回結(jié)果。

StreamingResponseBody
A StreamingResponseBody can be returned to write to the response OutputStream asynchronously; also supported as the body within a ResponseEntity.

用于異步write outputStream,使用的是Spring MVC的AsyncTaskExecutor,Spring MVC使用StreamingResponseBodyReturnValueHandler負(fù)責(zé)處理它。要注意,Spring MVC并沒有使用Servlet 3.1 Async IO([Read|Write]Listener)。

下面是例子StreamingResponseBodyController

@RestController
public class StreamingResponseBodyController {

  @RequestMapping("streaming-response-body-hello")
  public StreamingResponseBody hello() {

    return outputStream -> {
      String hello = new SlowJob("CallableController").doWork();
      outputStream.write(hello.getBytes());
      outputStream.flush();
    };

  }
}

用瀏覽器訪問:http://localhost:8080/streaming-response-body-hello 查看返回結(jié)果。

配置MVC Async AsyncTaskExecutor

Spring MVC執(zhí)行異步操作需要用到AsyncTaskExecutor,這個(gè)可以在用WebMvcConfigurer.configureAsyncSupport方法來提供(相關(guān)文檔)。
如果不提供,則使用SimpleAsyncTaskExecutor,SimpleAsyncTaskExecutor不使用thread pool,因此推薦提供自定義的AsyncTaskExecutor。

需要注意的是@EnableAsync也需要用到AsyncTaskExecutor,不過Spring MVC和它用的不是同一個(gè)。
順帶一提,EnableAsync默認(rèn)也使用SimpleAsyncTaskExecutor,可以使用AsyncConfigurer.getAsyncExecutor方法來提供一個(gè)自定義的AsyncTaskExecutor。

例子見:MvcAsyncTaskExecutorConfigurer。

Interceptors

AsyncHandlerInterceptor,使用WebMvcConfigurer.addInterceptors注冊(cè)

CallableProcessingInterceptor[Adapter],使用WebMvcConfigurer.configureAsyncSupport注冊(cè)

DeferredResultProcessingInterceptor[Adapter],使用WebMvcConfigurer.configureAsyncSupport注冊(cè)

官方文檔:Intercepting Async Requests

WebAsyncManager

WebAsyncManager是Spring MVC管理async processing的中心類,如果你可以閱讀它的源碼來更多了解Spring MVC對(duì)于async processing的底層機(jī)制。

參考資料

Spring Web MVC Doc - Supported method return values

Spring Web MVC Doc - Asynchronous Request Processing

Spring Web MVC Doc - Configuring Asynchronous Request Processing

Configuring Spring MVC Async Threads

Spring MVC 3.2 Preview: Introducing Servlet 3, Async Support

Spring MVC 3.2 Preview: Techniques for Real-time Updates

Spring MVC 3.2 Preview: Making a Controller Method Asynchronous

Spring MVC 3.2 Preview: Adding Long Polling to an Existing Web Application

Spring MVC 3.2 Preview: Chat Sample

文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請(qǐng)注明本文地址:http://systransis.cn/yun/70883.html

相關(guān)文章

  • 4.1、異步請(qǐng)求處理(TODO)

    摘要:本部分示例見這個(gè)項(xiàng)目的分支下的中引進(jìn)了基于異步請(qǐng)求處理的。同時(shí)主容器線程退出釋放并允許處理其他請(qǐng)求。對(duì)的調(diào)用返回,可以被用于異步處理之上的進(jìn)一步控制。 ??本部分示例見這個(gè)項(xiàng)目的 mvc 分支下的 AsyncController.java ??Spring MVC 3.2 中引進(jìn)了基于異步請(qǐng)求處理的 Servlet 3。除了返回一個(gè)值,一個(gè)控制器方法現(xiàn)在可以返回一個(gè)java.util...

    AbnerMing 評(píng)論0 收藏0
  • Spring核心 Spring簡介

    摘要:基于工廠,會(huì)有多種應(yīng)用上下文的實(shí)現(xiàn)的模塊在模塊中,面向切面編程提供了豐富的支持,該模塊是應(yīng)用系統(tǒng)中開發(fā)切面的基礎(chǔ),可以幫助應(yīng)用對(duì)象解耦。的主頁安全對(duì)于許多應(yīng)用都是一個(gè)非常關(guān)鍵的切面。 簡化Java開發(fā) JavaBean:Enterprise JavaBean、EJBJDO:Java數(shù)據(jù)對(duì)象、Java Data ObjectPOJO:Plain Old Java ObjectDI:依賴注...

    sixgo 評(píng)論0 收藏0
  • springmvc簡介和快速搭建

    摘要:簡介和眾多其他框架一樣,它基于的設(shè)計(jì)理念,此外,它采用可松散耦合可插拔組件結(jié)構(gòu),比其他框架更具擴(kuò)展性和靈活性??蚣車@核心展開,是框架的總導(dǎo)演,總策劃,它負(fù)責(zé)截獲請(qǐng)求并將其分派給相應(yīng)的處理器處理。 springmvc簡介 springmvc和眾多其他web框架一樣,它基于MVC的設(shè)計(jì)理念,此外,它采用可松散耦合可插拔組件結(jié)構(gòu),比其他MVC框架更具擴(kuò)展性和靈活性。 springmvc通過...

    Sike 評(píng)論0 收藏0
  • 后臺(tái) - 收藏集 - 掘金

    摘要:探究系統(tǒng)登錄驗(yàn)證碼的實(shí)現(xiàn)后端掘金驗(yàn)證碼生成類手把手教程后端博客系統(tǒng)第一章掘金轉(zhuǎn)眼間時(shí)間就從月份到現(xiàn)在的十一月份了。提供了與標(biāo)準(zhǔn)不同的工作方式我的后端書架后端掘金我的后端書架月前本書架主要針對(duì)后端開發(fā)與架構(gòu)。 Spring Boot干貨系列總綱 | 掘金技術(shù)征文 - 掘金原本地址:Spring Boot干貨系列總綱博客地址:http://tengj.top/ 前言 博主16年認(rèn)識(shí)Spin...

    CrazyCodes 評(píng)論0 收藏0

發(fā)表評(píng)論

0條評(píng)論

最新活動(dòng)
閱讀需要支付1元查看
<