视频直播系统源码,异步处理实现代码分析
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("doget"); method3(request,response); } /** * 使用asyncContext执行异步请求 * @param request * @param response */ public void method1(HttpServletRequest request, HttpServletResponse response) { //获取异步上下文 AsyncContext asyncContext = request.startAsync(); //开启异步处理过程 asyncContext.start(() -> { //耗时处理 try { Thread.sleep(2000); //通过AsyncContext返回 respsonse asyncContext.getResponse().getWriter().write("Hello World1!"); } catch (Exception e) { e.printStackTrace(); } //异步处理完成 asyncContext.complete(); }); } /** * 使用自身线程池来执行异步请求 * @param request * @param response */ public void method2(HttpServletRequest request, HttpServletResponse response) { AsyncContext asyncContext = request.startAsync(); Runnable runnable = () -> { try { Thread.sleep(2000); asyncContext.getResponse().getWriter().write("Hello World2!"); } catch (Exception e) { e.printStackTrace(); } asyncContext.complete(); }; new Thread(runnable).start(); } /** * 使用asyncContext.dispath()来重新提交请求 * @param request * @param response */ public void method3(HttpServletRequest request, HttpServletResponse response) { Object result = request.getAttribute("result"); if(result==null) { AsyncContext asyncContext = request.startAsync(); Runnable runnable = () -> { try { Thread.sleep(2000); // request.setAttribute("result", "Hello World3!"); } catch (Exception e) { e.printStackTrace(); } asyncContext.dispatch(); }; new Thread(runnable).start(); }else{ try { response.getWriter().write(result.toString()); } catch (Exception e) { e.printStackTrace(); } } }
上面列了AsyncContext使用的三种方式:
- commit(): 标识异步事件的结束,http通道关闭
- 使用AsyncConext线程池执行任务
- 使用业务线程池执行任务
- dispath(): 通知servlet容器,重新发起请求(doService()会收到两次请求)
以上就是视频直播系统源码,异步处理实现代码分析, 更多内容欢迎关注之后的文章
标签:异步,Thread,request,param,response,asyncContext,直播,源码 From: https://www.cnblogs.com/yunbaomengnan/p/18076711