您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
本篇文章给大家分享的是有关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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。