springmvc服务端怎样推送DeferredResult
本篇文章给大家分享的是有关spring mvc服务端怎样推送 DeferredResult,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。
成都创新互联从2013年成立,是专业互联网技术服务公司,拥有项目网站制作、做网站网站策划,项目实施与项目整合能力。我们以让每一个梦想脱颖而出为使命,1280元大厂做网站,已为上家服务,为大厂各地企业和个人服务,联系电话:13518219792
示例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 DeferredResultDeferredCall() { LOGGER.info("---请求开始---"); try { return handle(); } finally { LOGGER.info("---请求结束---"); } } private DeferredResult handle() { DeferredResult 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 DeferredResultdeferredResult() throws Exception { System.out.println("控制层执行线程:" + Thread.currentThread().getName()); //超时 DeferredResult deferredResult = new DeferredResult (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,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注创新互联行业资讯频道。
新闻名称:springmvc服务端怎样推送DeferredResult
网页路径:http://azwzsj.com/article/jiiioi.html