使用eclipse进行开发,创建一个普通的java工程,导入java-client.jar,这个jar包在bin/client目录下
1. 定义一个接口
public interface HelloWorldRemote {String sayHelloRemote();
}
2.定义一个ejb,实现这个接口,并且指定这个接口为remote接口
import javax.ejb.Remote;
import javax.ejb.Stateless;
@Stateless
@Remote(HelloWorldRemote.class)
public class HelloWorldRemoteBean implements HelloWorldRemote {
@Override
public String sayHelloRemote() {
// TODO Auto-generated method stub
return "say remote";
}
}
如果指定HelloWorldRemote 为local接口,那么在remote client就无法访问这个ejb
Local接口和remote接口也不可以是同一个接口
3.导出这些class为jar包,jar包名为helloworld1,部署到jboss中
4.客户端访问这个ejb
Properties props = new Properties();
props.put("java.naming.factory.initial","org.jboss.naming.remote.client.InitialContextFactory");
props.put("java.naming.provider.url", "remote://localhost:4447");
props.put("jboss.naming.client.ejb.context",true);
try{
InitialContext ctx = new InitialContext(props);
HelloWorldRemote helloworld = (HelloWorldRemote)(ctx.lookup("helloworld1//HelloWorldRemoteBean!com.alex.wang.HelloWorldRemote"));
System.out.println(helloworld.sayHelloRemote());
}catch(NamingException e){
System.out.println("get error");
System.out.println(e);
}
这里不能使用ejb:helloworld1//HelloWorldRemoteBean!com.alex.wang.HelloWorldRemote来访问
否则报Exception in thread "main" java.lang.IllegalStateException: EJBCLIENT000025: No EJB receiver available for handling [appName:helloworld1, moduleName:, distinctName:] combination for invocation context org.jboss.ejb.client.EJBClientInvocationContext@1af691b
原因应该是jndi前缀名为ejb:,但是我们没有指定其对应的interceptor
5.服务端访问这个ejb
在部署ejb的时候,server.log可以看出在server里每个ejb绑定的jndi,例如部署了一个helloworldbean,实现了helloworld接口
在jboss的server.log中,可以看出其绑定的jndi为
java:global/helloworld/HelloWorldBean!com.alex.wang.HelloWorld
java:app/helloworld/HelloWorldBean!com.alex.wang.HelloWorld
java:module/HelloWorldBean!com.alex.wang.HelloWorld
java:global/helloworld/HelloWorldBean
java:app/helloworld/HelloWorldBean
java:module/HelloWorldBean
那么在server中调用这个ejb,可以使用这样的方式
InitialContext ctx = new InitialContext();
HelloWorld world =(HelloWorld)ctx.lookup("java:global/helloworld1/HelloWorldBean!com.alex.wang.HelloWorld");
根据调用ejb与被调用ejb位置的关系,我们可以采用不同的jndi来进行调用(java:global,java:app,java:module)
上述的试验也说明在ejb3中,无需定义ejb-jar.xml
为什么通过4447端口可以获得ejb呢
原因是在jboss server的standalone.xml中定义了remoting模块
<extension module="org.jboss.as.remoting"/>
其相关的配置为
<subsystem xmlns="urn:jboss:domain:remoting:1.1">
<connector name="remoting-connector" socket-binding="remoting" security-realm="ApplicationRealm"/>
</subsystem>
其指定绑定端口为remoting
在<socket-binding-group中了定义其对应4447端口
<socket-binding name="remoting" port="4447"/>
而在 <subsystem xmlns="urn:jboss:domain:ejb3:1.3">,定义了其remote 访问使用的是前面定义的remoting-connector
<remote connector-ref="remoting-connector" thread-pool-name="default"/>
所以通过4447端口,remote 协议可以访问到ejb
本文详细介绍了如何使用Eclipse创建普通Java工程,导入jar包,定义接口和EJB,导出为jar包,部署到JBoss中,并通过客户端访问EJB的过程。同时解释了通过4447端口访问EJB的原因,以及服务端如何在JBoss中调用EJB。

4455

被折叠的 条评论
为什么被折叠?



