복붙노트

[SPRING] 비동기식으로 긴 폴링 구현

SPRING

비동기식으로 긴 폴링 구현

스레드로부터 HTTPServletRequest를 가져 와서이 스레드를 풀 (즉, 다시 풀로 가져옴) 할 수 있습니까?하지만 시간이 많이 소요되는 작업에서 결과를 얻을 때까지 브라우저와의 기본 연결을 유지하십시오 (예 : 처리 이미지)? 리턴 데이터가 처리 될 때, 다른 메소드는 비동기 적으로 호출되어야하며, 요청 및 데이터를 매개 변수로 제공해야합니다.

보통, 긴 풀링은 현재 스레드가 해체되지 않는 꽤 차단 방식으로 기능하므로 동시 연결 측면에서 서버 측 응용 프로그램의 확장 성이 저하됩니다.

해결법

  1. ==============================

    1.예, Servlet 3.0으로이 작업을 수행 할 수 있습니다.

    예, Servlet 3.0으로이 작업을 수행 할 수 있습니다.

    아래는 30 초마다 경고를 작성하는 샘플입니다 (테스트하지 않음).

    @WebServlet(async =“true”)
    public class AsyncServlet extends HttpServlet {
    
    Timer timer = new Timer("ClientNotifier");
    
    public void doGet(HttpServletRequest req, HttpServletResponse res) {
    
        AsyncContext aCtx = request.startAsync(req, res);
        // Suspend request for 30 Secs
        timer.schedule(new TimerTask(aCtx) {
    
            public void run() {
                try{
                      //read unread alerts count
                     int unreadAlertCount = alertManager.getUnreadAlerts(username); 
                      // write unread alerts count
        response.write(unreadAlertCount); 
                 }
                 catch(Exception e){
                     aCtx.complete();
                 }
            }
        }, 30000);
    }
    }
    

    다음은 이벤트를 기반으로 작성하는 샘플입니다. AlertNotificationHandler에 클라이언트에 경고해야한다고 알리는 alertManager를 구현해야합니다.

    @WebServlet(async=“true”)
    public class AsyncServlet extends HttpServlet {
     public void doGet(HttpServletRequest req, HttpServletResponse res) {
            final AsyncContext asyncCtx = request.startAsync(req, res);
            alertManager.register(new AlertNotificationHandler() {
                       public void onNewAlert() { // Notified on new alerts
                             try {
                                   int unreadAlertCount =
                                          alertManager.getUnreadAlerts();
                                   ServletResponse response = asyncCtx.getResponse();
                                   writeResponse(response, unreadAlertCount);
                                   // Write unread alerts count
                             } catch (Exception ex) {
                                   asyncCtx.complete();
                                   // Closes the response
                             }
                       }
            });
      }
    }
    
  2. ==============================

    2.네, 서블릿 스펙 버전을 사용하는 것이 가능합니다. 3.0. 구현 제가 권장 할 수있는 것은 부두 서버입니다. 여길 봐.

    네, 서블릿 스펙 버전을 사용하는 것이 가능합니다. 3.0. 구현 제가 권장 할 수있는 것은 부두 서버입니다. 여길 봐.

  3. from https://stackoverflow.com/questions/8081895/implementing-long-polling-in-an-asynchronous-fashion by cc-by-sa and MIT license