12.6. 与 Apache Camel 集成
12.6.1. 概述
Apache Camel 提供了使用 Bean 语言调用 OSGi 服务的简单方法。每当 Apache Camel 应用程序部署到 OSGi 容器时,这个功能都会自动可用,且不需要特殊配置。
12.6.2. registry 链
当将 Apache Camel 路由部署到 OSGi 容器时,CamelContext
会自动设置 registry 链以解析 Bean 实例:registry 链由 OSGi 注册表组成,然后是 Blueprint 注册表。现在,如果您尝试引用特定的 bean 类或 bean 实例,registry 会按如下方式解析 bean:
- 首先查找 OSGi 注册表中的 bean。如果指定了类名称,请尝试将其与 OSGi 服务的接口或类匹配。
- 如果在 OSGi 注册表中找不到匹配项,请重新回退到 Blueprint 注册表中。
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 集成。
当您使用此方法时,IOSGi 服务会被隐式导入。在这种情况下,不需要 显式导入 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>
当您使用此方法时,IOSGi 服务会被隐式导入。在这种情况下,不需要 显式导入 OSGi 服务。