要从Apache Camel的body()方法中获取值,您可以使用以下代码示例:
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.main.Main;
public class CamelExample {
public static void main(String[] args) throws Exception {
Main main = new Main();
main.addRouteBuilder(new MyRouteBuilder());
main.run();
}
static class MyRouteBuilder extends RouteBuilder {
@Override
public void configure() throws Exception {
from("direct:start")
.process(exchange -> {
// 从body()中获取值
String bodyValue = exchange.getIn().getBody(String.class);
System.out.println("Value from body: " + bodyValue);
})
.to("mock:result");
}
}
}
在上面的代码中,我们创建了一个CamelExample类,它包含了一个名为MyRouteBuilder的嵌套类,该类继承自RouteBuilder类。在MyRouteBuilder类中,我们定义了一个路由,从direct:start端点接收消息,并在处理器(processor)中从body()方法中获取值。然后,我们将该值打印到控制台上。
您可以使用以下代码将消息发送到direct:start端点:
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.impl.DefaultCamelContext;
public class CamelExampleTest {
public static void main(String[] args) throws Exception {
CamelContext context = new DefaultCamelContext();
context.start();
ProducerTemplate template = context.createProducerTemplate();
template.sendBody("direct:start", "Hello, Camel!");
Thread.sleep(1000);
context.stop();
}
}
在上面的代码中,我们创建了一个CamelExampleTest类,它使用ProducerTemplate将消息发送到direct:start端点。在这种情况下,我们发送的消息是"Hello, Camel!"。注意,我们在发送消息之后暂停了一秒钟,以确保路由有足够的时间来处理消息。
当您运行CamelExample和CamelExampleTest的代码时,您将在控制台上看到以下输出:
Value from body: Hello, Camel!
这表明我们成功地从body()方法中获取了值。