Camel Bean使用示例

x33g5p2x  于2022-09-28 转载在 其他  
字(1.9k)|赞(0)|评价(0)|浏览(260)

Camel 中的 Bean 组件将 bean 绑定到 Camel 消息交换。让我们看一个 Camel Bean 示例。

Camel bean组件示例

此示例的目的是展示您可以调用 Camel Bean 组件的方法:

public class MyRouteBuilder extends RouteBuilder {
  @Override
  public void configure() throws Exception {
    from("timer://myTimer?period=2000")
        .setBody()
        .simple("Hello World Camel fired at:")
        .bean(new MyBean(), "setTime(${body})")
        .bean(new MyBean(), "done()");
  }
}

如您所见,我们正在调用使用 MyBean 注册的 bean,传递 Camel 路由的主体(在第一种情况下)并且不传递任何参数(第二种情况)。

public class MyBean {
  public void setTime(String s) {
    System.out.println(s + new java.util.Date());
  }

  public void done() {
    System.out.println("Done");
  }
}

您可以使用以下 Camel main 运行示例:

import org.apache.camel.CamelContext;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
public class MainApp {
  public static void main(String[] args) throws Exception {

    // create a CamelContext         

    CamelContext camel = new DefaultCamelContext();
    camel.addRoutes(new MyRouteBuilder());

    // start is not blocking         

    camel.start();

    // so run for 10 seconds         

    Thread.sleep(10 _000);

    // and then stop nicely         

    camel.stop();
  }
}

您将看到每 2 秒调用一次 Bean,直到我们停止 Camel 上下文:

Hello World Camel fired at:Sun Feb 07 18:41:06 CET 2021 Done Hello World Camel fired at:Sun Feb 07 18:41:08 CET 2021 Done

动态调用 Camel Bean

在我们的示例中,我们静态调用了 Camel Bean。如果我们要包含 Bean 本身作为参数,我们可以使用通用 .bean 元素,如下例所示:

public void configure() throws Exception {
  from("quartz:foo?cron={{myCron}}").bean("myBean", "hello").log("${body}").bean("myBean", "bye").log("${body}");
}

使用泛型bean组件时,需要在注册表中绑定Camel Bean。最简单的方法是通过包含 @org.apache.camel.BindToRegistry 注释的配置类。例子:

import org.apache.camel.BindToRegistry;
import org.apache.camel.PropertyInject;
public class MyConfiguration {
  @BindToRegistry
  public MyBean myBean() {

    // this will create an instance of this bean with the name of the method (eg myBean)         

    return new MyBean();
  }
  public void configure() {
    // this method is optional and can be removed if no additional configuration is needed.     

  }
}

我们刚刚通过一个简单的示例介绍了如何使用 Camel Bean 组件

源代码位于:https://github.com/fmarchioni/masterspringboot/tree/master/camel/camel-bean

相关文章

微信公众号

最新文章

更多