Posted on 2008-06-12 08:45
blues 阅读(106)
评论(0) 编辑 收藏 所属分类:
EJB3
转自 posted on 2008-05-22 20:57 學習奮鬥 阅读(972) 评论(2) 编辑 收藏 所属分类: EJB3
服务器端代码:
HelloWorld.java:
1
import javax.ejb.Remote;
2
3
@Remote
4
public interface HelloWorld
{
5
public String sayHello(String s);
6
}
7
HelloWorldBean.java
1
import javax.ejb.Stateless;
2
3
import org.jboss.annotation.ejb.Clustered;
4
5
import cn.HelloWorld;
6
7
@Stateless
8
@Clustered
9
public class HelloWorldBean implements HelloWorld
{
10
11
public String sayHello(String s)
{
12
System.out.println(s);
13
return s;
14
}
15
16
}
上面第8行的@Clustered是必须的,因为我们需要使用Stateless Bean的集群功能。
分别在IP地址为:192.168.1.88和192.168.1.99机器上面安装JBOSS4.0.5GA,JBOSS4.0.5可以去下载文件名为jboss-installer-1.2.0.GA.jar的安装,安装的时候选择ejb3-clustered,再下面有一步时选择Advance,再在Name输入框输入all,其它默认就可以了。
两台机器上面都安装好之后,分别在两台机器上面启动jboss,启动的时候需要加参数:如IP为192.168.1.88的机器启动JBOSS,则为:run -c all -b 192.168.1.88
当两台机器的JBOSS都正常启动后,将上面的Stateless Bean打包成jar包,发布到其中一台%JBOSS_HOME%\server\all\farm目录下面,这样集群中的其它结点将自动发布这个jar包。
当发布完成之后,我们编写客户端:
Client.java
1
import java.util.Properties;
2
3
import javax.naming.InitialContext;
4
import javax.naming.NamingException;
5
6
public class Client
{
7
8
public static void main(String[] args)
{
9
Properties prop = new Properties();
10
prop.setProperty("java.naming.factory.initial",
11
"org.jnp.interfaces.NamingContextFactory");
12
prop.setProperty("java.naming.factory.url.pkgs",
13
"org.jboss.naming:org.jnp.interfaces");
14
prop.setProperty("java.naming.provider.url",
15
"192.168.1.88:1099,192.168.1.99:1099");
16
17
try
{
18
InitialContext ict = new InitialContext(prop);
19
HelloWorld helloWorld = (HelloWorld) ict
20
.lookup("HelloWorldBean/remote");
21
for (int i = 0; i < 10; i++)
{
22
helloWorld.sayHello("HelloWorld");
23
}
24
} catch (NamingException e)
{
25
e.printStackTrace();
26
}
27
}
28
}
29
上面这个客户端配置了JBOSS服务器IP地址及端口,调用远程接口的HelloWorldBean,并连续调用10次sayHello方法。在JBOSS控制台上面可以看到打印出HelloWorld。
程序运行结果发现:在192.168.1.88 的JBOSS控制台上面打印出4个HelloWorld,另一个JBOSS控制台上面则打印出6个HelloWorld。加起来正好10个HelloWorld,可以发现两台JBOSS已经实现了负载均衡。
集群中的任何一个结点挂掉之后,程序都可以正常运行,