Apache Camel: How to send two http requests in parallel and wait for the responses?

旧城冷巷雨未停 提交于 2019-12-10 11:23:18

问题


In Apache Camel, where I am defining a route, how can I send two or more http requests in parallel and wait on their 'futures'to get the responses for further processing like in Java with AsyncHttpClient?

AsyncHttpClient asyncHttpClient = new DefaultAsyncHttpClient();
Future<Response> f = asyncHttpClient.prepareGet("http://www.example.com/").execute();
Response r = f.get();

Just for the context, the following route calls the GET contacts http call and returns the response synchronously.

from("direct:getContact")
.to("http://host:port/contacts/1453")

回答1:


Try to split You route into many smaller routes. Then You can perform necessary unmarshalling there.

See question about unmarshalling http response

from("direct:getContact")
    .process(new Processor() {
        @Override
        public void process(Exchange exchange) throws Exception {
            CamelContext context = exchange.getContext();
            ProducerTemplate producerTemplate = context.createProducerTemplate();

            // Asynchronous call to internal route
            Future<Contact> contact = 
                producerTemplate.asyncRequestBody("direct:invokeSomeRestApi", null, Contact.class);  

            // Do rest of the work
            exchange.getOut().setBody(contact.get());
        }
    });

// Unmarshalling REST response
JacksonDataFormat jacksonDataFormat = new JacksonDataFormat();
jacksonDataFormat.setUnmarshalType(Contact.class);

// Internal route definition
from("direct:invokeSomeRestApi")
    .to("http://localhost:8080/api/contact/2345")
    .unmarshal(jacksonDataFormat);


来源:https://stackoverflow.com/questions/37388376/apache-camel-how-to-send-two-http-requests-in-parallel-and-wait-for-the-respons

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!