A synchronous jersey-rest service that initiates a background job?

This is the problem I am facing that is related to design and implementation:

I have a REST web service that accepts POST requests. There is nothing special about this. He is currently responding synchronously.

However, this web service is about to initiate a background process, which may take some time.

I do not want this service to respond in 30 minutes.

Instead, it should immediately return an ack response to the client, and nothing more (even after 30 minutes the information will no longer be sent).

How do I implement this behavior with Jersey?

I read the page https://jersey.java.net/nonav/documentation/2.0/async.html#d0e6914 .

Although it was an interesting read, I did not find a way to send only an ACK response (something like HTTP 200 code).

Perhaps I am confused with asynchronous and the behavior that I want to implement.

I just realized that I could create a new thread in my @POST method to process the background process and immediately return the ACK response.

But does this new thread work after the response has been sent back to the client?

How would you implement this WS?

I hope you can help me clarify this point.

+3
source share
1 answer

I think the Jersey 2 Asynchronous Server API associated with you will still maintain a client connection until processing is complete. Asynchronous processing is truly internal to Jersey and does not affect customer experience.

If you want to return the ACK, you can use the usual Jersey method, delegate the work to another thread and return immediately. I would recommend HTTP 202 for this use case.

You can create a Thread for this, as in the example with Jersey 2, and it will survive the execution of the call to the resource method in Jersey:

@POST public Response asyncPost(String data) { new Thread(...).start(); return Response.status(Response.Status.ACCEPTED).build(); } 

As said, creating threads is usually not recommended on application servers.

If you use EE7, I would recommend that you look at JSR-236 http://docs.oracle.com/javaee/7/api/javax/enterprise/concurrent/package-summary.html

If you use EE6, you might consider sending a message to the queue, which will be processed using Message-Driven Beans (MDB) in the background.

+4
source

Source: https://habr.com/ru/post/973176/


All Articles