RMI 是java实现透明远程调用的重要机制。在远程调用中,客户端仅有服务器端提供的接口。通过此接口实现对远程服务器端的调用。
Sun JDK 6.0以前版本中的RMI实现均基于TCP/IP+BIO方式。RMI要求服务器端的接口继承Remote接口,接口上的每种方法必须抛出RemoteException,服务器端业务类需实现此接口,然后通过调用UnicastRemoteObject.exportObject来将此对象帮定到某端口上,最后将此对象注册到本地的LocateRegistry上。
1.1 服务端代码
//服务端对外提供的接口
Public interface Hello extends Remote{
public String sayHello(String name) throws RemoteException;
}
实现类有两种方式:
1. 创建实例对象时绑定到某端口.通过继承UnicastRemoteObject(也可以用组合的方式)来实现
Public class HelloImpl extends UnicastRemoteObject implements Hello{
private static final long serialVersionUID = 1L;
Public HelloImpl() throws RemoteException {
super();
// TODO Auto-generated constructor stub
}
public String sayHello(String name) throws RemoteException {
// TODO Auto-generatedmethod stub
return "welcome,"+name;
}
}
启动的方式也有两种:
1) 通过java.rmi.Naming来启动
//使用默认端口
LocateRegistry.createRegistry(1099);
Naming.rebind("hello", new HelloImpl());
//使用不同的端口
LocateRegistry.createRegistry(8888);
Naming.rebind("rmi://10.225.112.86:8888/hello",new HelloImpl());
2) 通过java.rmi.registry.Registry来启动
//指定端口(默认端口是1099)
LocateRegistry.createRegistry(1099);
registry.rebind("hello", new HelloImpl());
2. 手动绑定到某端口. UnicastRemoteObject.exportObject来实现
Public class OtherHelloImpl implements Hello{
private static final long serialVersionUID = 1L;
public String sayHello(String name) throws RemoteException {
// TODO Auto-generatedmethod stub
return "welcome,"+name;
}
}
启动的方式也有两种:
1) 通过java.rmi.Naming来启动
//手动绑定到某端口
OtherHelloImpl otherHelloImpl=new OtherHelloImpl();
UnicastRemoteObject.exportObject(otherHelloImpl, 0);
//使用默认端口
LocateRegistry.createRegistry(1099);
Naming.rebind("hello", new HelloImpl());
//使用不同的端口
LocateRegistry.createRegistry(8888);
Naming.rebind("rmi://10.225.112.86:8888/hello",new HelloImpl());
2) 通过java.rmi.registry.Registry来启动
//手动绑定到某端口
OtherHelloImpl otherHelloImpl=new OtherHelloImpl();
UnicastRemoteObject.exportObject(otherHelloImpl,0);
//指定端口(默认端口是1099)
LocateRegistry.createRegistry(1099);
registry.rebind("hello", new HelloImpl());
1.2 客户端代码
1) 通过java.rmi.Naming来访问
Hello hello=(Hello)Naming.lookup("rmi://10.225.112.86:8888/hello"); hello.sayHello("呵呵");
2) 通过java.rmi.registry.Registry来访问
Registry registry=LocateRegistry.getRegistry("10.225.112.86",8888);
Hello hello=(Hello)registry.lookup("hello");
hello.sayHello("呵呵");
1.3 注意
1. rebind方法和bind方法的区别:
Bind不允许重复绑定,而rebind可以。