Finishing a HttpServletResponse but continue processing

后端 未结 4 1122
不思量自难忘°
不思量自难忘° 2021-02-15 11:14

I have a situation that seems to fit the Async Servlet 3.0 / Comet situation but all I need to do is return a 200 response code (or other) after accepting the incoming parameter

相关标签:
4条回答
  • 2021-02-15 11:57

    Here's how I've handled this situation:

    1. When the app starts up, create an ExecutorService with Executors.newFixedThreadPool(numThreads) (there are other types of executors, but I suggest starting with this one)
    2. In doPost(), create an instance of Runnable which will perform the desired processing - your task - and submit it to the ExecutorService like so: executor.execute(task)
    3. Finally, you should return the HTTP Status 202 Accepted, and, if possible, a Location header indicating where a client will be able to check up on the status of the processing.

    I highly recommend you read Java Concurrency in Practice, it's a fantastic and very practical book.

    0 讨论(0)
  • 2021-02-15 11:57

    On possibility for your servlet to accept a request for processing in the background, is for the servlet to hand off processing to a separate thread which then executes in the background.

    Using Spring, you can invoke a separate Thread using the a TaskExecutor. The advantage of using spring over standard JDK 5 java.util.concurrent.Executor is that if you're on application servers that need to use managed threads (IBM websphere or Oracle weblogic), you can use the WorkManagerTaskExecutor to hook into the CommonJ work managers.

    Another alternative would be to move the long query logic into a Message Driven Bean or Message Driven POJO (Spring JMS can help here) and let the servlet simply post a message on a JMS queue. That would have the advantage that should the load on your web container become too great because of your long running query, you could easily move the MDB onto a different (dedicated) system.

    0 讨论(0)
  • 2021-02-15 12:07

    You can continue processing in a separate Thread.

    The response is commited once you return from doPost() method.

    0 讨论(0)
  • 2021-02-15 12:10

    This example can help

    void doPost(){
        // do something
       final ExecutorService executor = Executors.newSingleThreadExecutor();
          executor.execute(new Runnable() {
              @Override
              public void run() {
                  // processing after response
              }
          });}
    
    0 讨论(0)
提交回复
热议问题