您好,登錄后才能下訂單哦!
本篇文章給大家分享的是有關spring mvc服務端怎樣推送 DeferredResult,小編覺得挺實用的,因此分享給大家學習,希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。
示例1:
package com.example.demo.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.context.request.async.DeferredResult; import java.time.LocalDateTime; import java.util.concurrent.TimeUnit; @Controller public class PushController { private static final Logger LOGGER = LoggerFactory.getLogger(PushController.class); @RequestMapping("/deferre") @ResponseBody public DeferredResult<String> DeferredCall() { LOGGER.info("---請求開始---"); try { return handle(); } finally { LOGGER.info("---請求結束---"); } } private DeferredResult<String> handle() { DeferredResult<String> deferredResult = new DeferredResult<>(); new Thread(() -> { try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); } LOGGER.info("---填充值---"); deferredResult.setResult(LocalDateTime.now().toString()); }).start(); return deferredResult; } }
示例2:
@RestController public class PiceaServletContoller { @Autowired private PiceaService piceaService; @RequestMapping("/deferredresult") public DeferredResult<String> deferredResult() throws Exception { System.out.println("控制層執行線程:" + Thread.currentThread().getName()); //超時 DeferredResult<String> deferredResult = new DeferredResult<String>(10*1000L); deferredResult.onTimeout(new Runnable() { @Override public void run() { System.out.println("異步線程執行超時"); deferredResult.setResult("線程執行超時"); } }); deferredResult.onCompletion(new Runnable() { @Override public void run() { System.out.println("異步執行完畢"); } }); FIXED_THREAD_POOL.execute(new Runnable() { @Override public void run() { System.out.println("異步執行線程:" + Thread.currentThread().getName()); try { String str = piceaService.task2(); Thread.sleep(1000); deferredResult.setResult("這是【異步】的請求返回: " + str); } catch (InterruptedException e) { e.printStackTrace(); }catch (Exception e) { e.printStackTrace(); } } }); return deferredResult; } /** * 線程池 */ public static ExecutorService FIXED_THREAD_POOL = Executors.newFixedThreadPool(10); }
以上就是spring mvc服務端怎樣推送 DeferredResult,小編相信有部分知識點可能是我們日常工作會見到或用到的。希望你能通過這篇文章學到更多知識。更多詳情敬請關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。