Apache Camel:如何并行发送两个 http 请求并等待响应? [英] Apache Camel: How to send two http requests in parallel and wait for the responses?

查看:109
本文介绍了Apache Camel:如何并行发送两个 http 请求并等待响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在定义路由的 Apache Camel 中,如何并行发送两个或多个 http 请求并等待它们的未来"获取响应以进行进一步处理,例如在 Java 中使用 AsyncHttpClient?

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();

仅就上下文而言,以下路由调用 GET 联系人 http 调用并同步返回响应.

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")

推荐答案

尝试将您的路线拆分为许多更小的路线.然后您可以在那里执行必要的解组.

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

参见关于解组http响应的问题

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);

这篇关于Apache Camel:如何并行发送两个 http 请求并等待响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆