Spring Boot(Spring MVC)では、リクエストはデフォルトで同期されます。スレッドは、リクエストの過去と終わりに責任があります。多くの場合、スループットを改善するためには、一部の操作を非同期化する必要があります。非同期にできる時間のかかるビジネスロジックに加えて、クエリインターフェイスも非同期に実行できます。
サービスへのリクエストは、スレッドHTTP-NIO-8084-EXEC-1などのWebコンテナからのスレッドによって受信されます
WebAsynctaskを使用して、このリクエストを実行のために新しいスレッドに配布できます。HTTP-NIO-8084-EXEC-1は、他のリクエストの処理を受信できます。 WebAsynctaskがデータを返すと、呼び出されて再度処理され、値は非同期で要求側に返されます。
サンプルコードは次のとおりです。
@RequestMapping(value = "/login"、method = requestmethod.get)public webasynctask <modelsview> longtimetask(){system.out.println( "/loginはスレッドidと呼ばれます:" + thread.currentthread()。 callable <modelandview> callable = new callable <modelandview>(){public modelandview call()throws exception {thread.sleep(1000); /長期タスクをシミュレートModelandView Mav = new ModelandView( "Login/Index"); system.out.println( "実行成功したスレッドIDは:" + thread.currentThread()。getName()); mavを返します。 }};新しいwebasynctask <modelandview>(呼び出し可能);}出力の結果は次のように表示できます。
/ログインはスレッドIDと呼ばれます:HTTP-NIO-8084-EXEC-1
実行に正常にスレッドIDがmvcasync1です
ビジネスロジックを実行する前のスレッドと、ビジネスロジックを具体的に扱うスレッドは同じではなく、目標を達成します。
その後、私は同時テストを行い、MVCASYNC1スレッドを常に作成していることがわかりました。私は考えていました、スレッドプールは使用されていませんか?
ソースコードを読んだ後、これが真実であることがわかりました。 WebAsyncManagerは、非同期処理を管理するスプリングMVCの中央クラスです。
デフォルトは、simpleasynctaskexecutorを使用することです。これにより、各リクエストの新しいスレッドが作成されます。
private asynctaskexecutor taskexecutor = new simpleasynctaskexecutor(this.getClass()。getSimplename());
タスクが執行者を指定する場合、タスクを使用して指定します。そうでない場合は、デフォルトのsimpleasynctaskexecutorを使用してください
asynctaskexecutor executor = webasynctask.getExecutor(); if(executor!= null){this.taskexecutor = executor;}タスクごとに個別に指定することなく、Asyncのスレッドプールを構成できます
configurer.settaskexecutor(threadpooltaskexecutor())によって指定
Import org.springframework.context.annotation.bean; Import org.springframework.context.annotation.configuration; Import org.springframework.concurrent.threadpooltaskexecutor; Import org.springframework.web.context.request.async.timeoutprocessinginterceptor; import org.springframework.web.servlet.config.annotation.asyncsupportconfigurer; Import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;@Configurationpublic class WebMvcConfig extends WebMvcConfigurationSupport { @Override public void configureAsyncSupport(final AsyncSupportConfigurer configure) { configurer.setDefaultTimeout(60 * 1000L); configurer.registerCallableInterceptors(timeoutInterceptor()); configurer.settaskexecutor(threadpooltaskexecutor()); } @bean public timeoutcallableprocessinginterceptor timeoutInterceptor(){return new TimeOutCallableProcessInginterceptor(); } @bean public threadpooltaskexecutor threadpooltaskexecutor(){threadpooltaskexecutor t = new swerchpooltaskexecutor(); T.SetCorepoolsize(10); t.setmaxpoolsize(50); t.setThreadNamePrefix( "yjh"); tを返します。 }}構成後、出力スレッド名がYJHで始まり、新しいスレッドは常に作成されないことがわかります。
出力の結果は次のように表示できます。
/ログインはスレッドIDと呼ばれます:http-nio-8084-exec-1実行スレッドIDは次のとおりです。
要約します
上記は、編集者がSpring Bootに導入したもので、WebAsynctaskを使用して結果を非同期に返します。私はそれが誰にでも役立つことを願っています。ご質問がある場合は、メッセージを残してください。編集者は、すべての人に時間内に返信します。 wulin.comのウェブサイトへのご支援ありがとうございます!