12.6. 与 Apache Camel 集成

12.6.1. 概述

Apache Camel 提供了使用 Bean 语言调用 OSGi 服务的简单方法。当 Apache Camel 应用程序部署到 OSGi 容器中且不需要特殊配置时,此功能会自动可用。

12.6.2. registry 链

当 Apache Camel 路由部署到 OSGi 容器中时,CamelContext 会自动设置用于解析 bean 实例的 registry 链:registry 链由 OSGi 注册表组成,后跟 Blueprint registry。现在,如果您尝试引用特定的 bean 类或 bean 实例,registry 会解析 bean,如下所示:

  1. 首先在 OSGi 注册表中查找 bean。如果指定了类名称,请尝试与 OSGi 服务的接口或类匹配。
  2. 如果在 OSGi 注册中心中没有找到匹配项,请回退到 Blueprint registry。

12.6.3. OSGi 服务接口示例

考虑由以下 Java 接口定义的 OSGi 服务,它定义了单一方法 getGreeting ()

package org.fusesource.example.hello.boston;

public interface HelloBoston {
    public String getGreeting();
}

12.6.4. 服务导出示例

在定义实现 HelloBoston OSGi 服务的捆绑包时,您可以使用以下 Blueprint 配置导出服务:

<?xml version="1.0" encoding="UTF-8"?>
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0">

  <bean id="hello" class="org.fusesource.example.hello.boston.HelloBostonImpl"/>

  <service ref="hello" interface="org.fusesource.example.hello.boston.HelloBoston"/>

</blueprint>

假设 HelloBoston 接口由 HelloBostonImpl 类(未显示)实现。

12.6.5. 从 Java DSL 调用 OSGi 服务

部署包含 HelloBoston OSGi 服务的捆绑包后,您可以使用 Java DSL 从 Apache Camel 应用程序调用该服务。在 Java DSL 中,您可以通过 Bean 语言调用 OSGi 服务,如下所示:

from("timer:foo?period=5000")
  .bean(org.fusesource.example.hello.boston.HelloBoston.class, "getGreeting")
  .log("The message contains: ${body}")

bean 命令中,第一个参数是 OSGi 接口或类,它必须与从 OSGi 服务捆绑包导出的接口匹配。第二个参数是您要调用的 bean 方法的名称。有关 bean 命令语法的详情,请参阅 Apache Camel 开发指南 Bean 集成

注意

使用这种方法时,将隐式导入 OSGi 服务。在这种情况下,不需要显式 导入 OSGi 服务。

12.6.6. 从 XML DSL 调用 OSGi 服务

在 XML DSL 中,您还可以使用 Bean 语言调用 HelloBoston OSGi 服务,但语法略有不同。在 XML DSL 中,您可以使用 method 元素通过 Bean 语言调用 OSGi 服务,如下所示:

<beans ...>
  <camelContext xmlns="http://camel.apache.org/schema/spring">
    <route>
      <from uri="timer:foo?period=5000"/>
      <setBody>
          <method ref="org.fusesource.example.hello.boston.HelloBoston" method="getGreeting"/>
      </setBody>
      <log message="The message contains: ${body}"/>
    </route>
  </camelContext>
</beans>
注意

使用这种方法时,将隐式导入 OSGi 服务。在这种情况下,不需要显式 导入 OSGi 服务。