搜索

92.4. 例子

download PDF

在以下示例中,我们使用定义如下的 Greater EJB:

GreaterLocal.java

public interface GreaterLocal {

    String hello(String name);

    String bye(String name);

}

和实施

GreaterImpl.java

@Stateless
public class GreaterImpl implements GreaterLocal {

    public String hello(String name) {
        return "Hello " + name;
    }

    public String bye(String name) {
        return "Bye " + name;
    }

}

92.4.1. 使用 Java DSL

在本例中,我们将要在 EJB 上调用 hello 方法。由于本示例基于使用 Apache Openejb 的单元测试,我们必须使用 Openejb 设置在 EJB 组件上设置 JndiContext

@Override
protected CamelContext createCamelContext() throws Exception {
    CamelContext answer = new DefaultCamelContext();

    // enlist EJB component using the JndiContext
    EjbComponent ejb = answer.getComponent("ejb", EjbComponent.class);
    ejb.setContext(createEjbContext());

    return answer;
}

private static Context createEjbContext() throws NamingException {
    // here we need to define our context factory to use OpenEJB for our testing
    Properties properties = new Properties();
    properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.openejb.client.LocalInitialContextFactory");

    return new InitialContext(properties);
}

然后,我们已准备好在 Camel 路由中使用 EJB:

from("direct:start")
    // invoke the greeter EJB using the local interface and invoke the hello method
    .to("ejb:GreaterImplLocal?method=hello")
    .to("mock:result");

在实际的应用服务器中

在实际的应用服务器中,您可能不必在 EJB 组件上设置 JndiContext,因为它将在与应用服务器相同的 JVM 上创建默认的 JndiContext,这通常允许它访问 JNDI 注册表并查找 EJB。但是,如果您需要访问远程 JVM 或类似的应用服务器,您必须事先准备属性。

92.4.2. 使用 Spring XML

这是使用 Spring XML 的同一示例:

同样,这基于单元测试,因此我们需要设置 EJB 组件:

<!-- setup Camel EJB component -->
<bean id="ejb" class="org.apache.camel.component.ejb.EjbComponent">
    <property name="properties" ref="jndiProperties"/>
</bean>

<!-- use OpenEJB context factory -->
<p:properties id="jndiProperties">
    <prop key="java.naming.factory.initial">org.apache.openejb.client.LocalInitialContextFactory</prop>
</p:properties>

在 Camel 路由中使用 EJB 之前:

<camelContext xmlns="http://camel.apache.org/schema/spring">
    <route>
        <from uri="direct:start"/>
        <to uri="ejb:GreaterImplLocal?method=hello"/>
        <to uri="mock:result"/>
    </route>
</camelContext>
Red Hat logoGithubRedditYoutubeTwitter

学习

尝试、购买和销售

社区

关于红帽文档

通过我们的产品和服务,以及可以信赖的内容,帮助红帽用户创新并实现他们的目标。

让开源更具包容性

红帽致力于替换我们的代码、文档和 Web 属性中存在问题的语言。欲了解更多详情,请参阅红帽博客.

關於紅帽

我们提供强化的解决方案,使企业能够更轻松地跨平台和环境(从核心数据中心到网络边缘)工作。

© 2024 Red Hat, Inc.