Apache Camel - 动态构建端点

Apache Camel - Build both from and to endpoints dynamically

我有一条骆驼路线,它处理来自 process queue 的消息并将其发送到 upload queue

from("activemq:queue:process" ).routeId("activemq_processqueue")
        .process(exchange -> {
            SomeImpl impl = new SomeImpl();
            impl.process(exchange);
        })
        .to(ExchangePattern.InOnly, "activemq:queue:upload");

impl.process 中,我正在填充 Iddestination server path。现在我需要定义一个新路由,它使用来自上传队列的消息,并复制一个本地文件夹(基于之前路由中生成的 Id)并将其上传到目标文件夹,这是一个 ftp 服务器(这也填充在以前的路线)

那么如何设计一条新路线,其中起点和终点都是动态的,如下所示?

from("activemq:queue:upload" )
        .from("file:basePath/"+{idFromExchangeObject})
    .to("ftp:"+{serverIpFromExchangeObject}+"/"+{pathFromExchangeObject});

在 Camel 中向端点添加动态(如评论中所述)可以使用 .toD() 来完成,on this page on the Camel site. 我不知道有任何 fromD() 等效项。但是,您可以通过调用 CamelContext 上的 addRoutes 方法来添加动态路由。这在 this page on the Camel site.

上有描述

稍微扩展这里来自 Camel 站点的示例应该会让您朝着正确的方向前进。

public void process(Exchange exchange) throws Exception {
   String idFromExchangeObject = ...
   String serverIpFromExchangeObject = ...
   String pathFromExchangeObject = ...

   exchange.getContext().addRoutes(new RouteBuilder() {
       public void configure() {
           from("file:basePath/"+ idFromExchangeObject)
            .to("ftp:"+ serverIpFromExchangeObject +"/"+pathFromExchangeObject);
       }
   });
}

Camel 中可能还有其他选项,因为该框架具有数量惊人的 EIP 和功能。

我认为你的情况有更好的选择,当然你使用的是比 2.16 更新的 Camel 版本。(以前版本的替代品存在,但更复杂而且看起来不优雅 -(例如 consumerTemplate & recipientList).

您可以将第一个 "dynamic from" 替换为 pollEnrich,它使用轮询使用者和简单表达式来丰富消息以构建动态文件端点。对于第二部分,如前所述,动态 uri .toD 将完成这项工作。所以你的路线看起来像这样:

 from("activemq:queue:upload" )
    .pollEnrich().simple("file:basePath/${header.idFromExchangeObject})
    .aggregationStrategy(new ExampleAggregationStrategy()) // * see explanation 
    .timeout(2000) // the timeout is optional but recommended
    .toD("ftp:${header.serverIpFromExchangeObject}/${header.pathFromExchangeObject}") 
  1. 查看内容丰富部分 "Using dynamic uris" http://camel.apache.org/content-enricher.html.

    您将需要一个聚合策略,将原始交换与资源交换结合起来,以确保 headers serverIpFromExchangeObject、pathFromExchangeObject 在丰富后包含在聚合交换中。如果您不包含自定义策略,Camel 将默认使用从资源中获取的 body。查看 content-enricher.html 中的 ExampleAggregationStrategy 示例,了解其工作原理。

  2. 对于 .toD(),请查看 http://camel.apache.org/how-to-use-a-dynamic-uri-in-to.html