java camel <from uri_让Camel处理各种URI类型

我相信一个难点是,对于您提到的组件(HTTP,FTP,文件,JMS),您可能想要使用生产者或消费者:

FTP,File:绝对是读取文件的消费者。

HTTP(或HTTP4):绝对是生产者,向服务器发送请求(服务器的回复将由新邮件正文)

JMS:取决于您想要从队列(消费者)读取数据,或者使用ReplyTo标头将消息发送到队列,然后等待答案(生产者)。

制作人:

如果您使用的是Camel 2.16+,则可以使用新的"dynamic to"语法。它基本上与常规“to”相同,除了可以使用simple表达式(或者,optionnaly,另一种表达式)动态评估端点uri。或者,你可以使用content-enricher pattern的enrich风格,它也支持从Camel 2.16开始的动态uris。

如果您使用的是较旧版本的Camel,或者您需要动态路由到多个端点(而不仅仅是一个端点),则可以使用recipient list模式。

这是一个例子。我们将通过调用端点来转换消息体;该端点的uri将在名为TargetUri的标头中找到,并将针对每条消息动态评估。

// An instance of this class is registered as 'testbean' in the registry. Instead of

// sending to this bean, I could send to a FTP or HTTP endpoint, or whatever.

public class TestBean {

public String toUpperCase(final String str) {

return str.toUpperCase();

}

}

// This route sends a message to our example route for testing purpose. Of course, we

// could send any message as long as the 'TargetUri' header contains a valid endpoint uri

from("file:inbox?move=done&moveFailed=failed")

.setHeader("TargetUri").constant("bean:testbean?method=toUpperCase")

.setBody().constant("foo")

.to("direct:test");

// 1. The toD example :

from("direct:test")

.toD("${header.TargetUri}")

.to("log:myRoute");

// 2. The recipient list example :

from("direct:test")

.recipientList(header("TargetUri"))

.to("log:myRoute");

// 3. The enrich example :

from("direct:test")

.enrich().simple("${header.TargetUri}") // add an AggregationStrategy if necessary

.to("log:myRoute");

消费者:

使用Camel 2.16 +,您可以使用content-enricher pattern的pollEnrich风格。

对于旧版本的Camel,您可以在处理器中使用ConsumerTemplate。

// 4. The pollEnrich example (assuming the TargetUri header contains, e.g., a file

// or ftp uri) :

from("direct:test")

.pollEnrich().simple("${header.TargetUri}") // add an AggregationStrategy if necessary

.to("log:myRoute");

// 5. The ConsumerTemplate example (same assumption as above)

from("direct:test")

.process(new Processor() {

@Override

public void process(Exchange exchange) throws Exception {

String uri = exchange.getIn().getHeader("TargetUri", String.class);

ConsumerTemplate consumer = exchange.getContext().createConsumerTemplate();

final Object data = consumer.receiveBody(uri);

exchange.getIn().setBody(data);

}

})

.to("log:myRoute");

制作人或消费者?

可悲的是,我想不出任何真正优雅的解决方案来处理两者 - 我认为你必须根据uri和已知的组件路由到两个分支......这就是我可能做的事情(与Camel一起) 2.16 +),它不是很漂亮:

// This example only handles http and ftp endpoints properly

from("direct:test")

.choice()

.when(header("TargetUri").startsWith("http"))

.enrich().simple("${header.TargetUri}")

.endChoice()

.when(header("TargetUri").startsWith("ftp"))

.pollEnrich().simple("${header.TargetUri}")

.endChoice()

.end()

.to("log:myRoute");