neu242
neu242

Reputation: 16575

How do I make an Apache Camel Servlet request return immediately?

I want a request to an Apache Camel Servlet to return immediately, but continue processing the request in a "background" thread. I've tried several things, but it seems it still is processing a lot before returning.

from("servlet://my-endpoint")
            .threads()
            .process(exchange -> {
                exchange.getOut().setBody(doStuff(exchange.getHeaders()))
            })
            .multicast()
            .parallelProcessing()
            .recipientList(constant("direct:a,direct:b,direct:c"), ",")
            .ignoreInvalidEndpoints()
            .transform()
            .constant("OK");

I test using curl:

curl 'http://localhost:4000/my-app/camel/my-endpoint' -X POST --data 'myVar=bar&myOtherVar=foo'

Any ideas what I'm doing wrong?

Upvotes: 0

Views: 1074

Answers (3)

neu242
neu242

Reputation: 16575

I got a hint on using ProducerTemplate instead. Turns out it works great:

from("servlet://my-endpoint")
  .process(exchange -> {
    Map body = doStuff(exchange.getIn().getHeaders()));
    ProducerTemplate template = exchange.getContext().createProducerTemplate();

    Arrays.asList("direct:a", "direct:b", "direct:c")
      .forEach(endpoint -> template.asyncSendBody(endpoint, body));
  });

EDIT: Warning! After using asyncSendBody in production, the machine went out of PIDs pretty fast. I'll have to figure out why Camel isn't releasing them...

Upvotes: 1

rak22
rak22

Reputation: 338

camel servlet supports async mode, take a look at camel documentation http://camel.apache.org/servlet.html Using Servlet 3.0 Async Mode

using wireTap is also an alternative. http://camel.apache.org/wire-tap.html

Upvotes: 1

Vadim
Vadim

Reputation: 4120

Because you use multicast main thread is waiting for response.

You just do your stuff in different threads, but in synchronous mode. If you'd like to make it completely asynchronous, use wireTap to another route endpoint at the very beginning.

Pseudo code logic:

main route:  
         from-> wireTap exchange ->to(process_endpoint) -> set immediate response.
process route: from(process_endpoint) -> do all stuff -> stop route.       

Upvotes: 3

Related Questions