影片直播系統原始碼,非同步處理實現程式碼分析

云豹科技-苏凌霄發表於2024-03-16

影片直播系統原始碼,非同步處理實現程式碼分析

 @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()會收到兩次請求)

以上就是影片直播系統原始碼,非同步處理實現程式碼分析, 更多內容歡迎關注之後的文章

相關文章