RMI浅析
1.RMI(Remote Method Invocation,远程方法调用)是Java的一组拥护开发分布式应用程序的API.RMI是很多RPC框架的基础.如常用的dubbo.

2. RMI demo
1.server端
/**
* 远程接口必须扩展接口java.rmi.Remote
*/
public interface HelloInterface extends Remote
{
/**
* 远程接口方法必须抛出 java.rmi.RemoteException
*/
public String say() throws RemoteException;
}
/**
* 扩展了UnicastRemoteObject类,并实现远程接口 HelloInterface
*/
class Hello extends UnicastRemoteObject implements HelloInterface
{
private String message;
/**
* 必须定义构造方法,即使是默认构造方法,也必须把它明确地写出来,因为它必须抛出出RemoteException异常
*/
public Hello(String msg) throws RemoteException
{
message = msg;
}
/**
* 远程接口方法的实现
*/
public String say() throws RemoteException
{
System.out.println("Called by HelloClient");
return message;
}
}
public class HelloServer
{
/**
* 启动 RMI 注册服务并进行对象注册
*/
public static void main(String[] argv)
{
try
{
//启动RMI注册服务,指定端口为1099 (1099为默认端口)
//也可以通过命令 $java_home/bin/rmiregistry 1099启动
//这里用这种方式避免了再打开一个DOS窗口
//而且用命令rmiregistry启动注册服务还必须事先用RMIC生成一个stub类为它所用
LocateRegistry.createRegistry(1099);
//创建远程对象的一个或多个实例,下面是hello对象
//可以用不同名字注册不同的实例
HelloInterface hello = new Hello("Hello, world!");
//把hello注册到RMI注册服务器上,命名为Hello
Naming.rebind("Hello", hello);
//如果要把hello实例注册到另一台启动了RMI注册服务的机器上
//Naming.rebind("//192.168.1.105:1099/Hello",hello);
System.out.println("Hello Server is ready.");
}
catch (Exception e)
{
System.out.println("Hello Server failed: " + e);
}
}
}
2.client 调用端
public class HelloClient
{
/**
* 查找远程对象并调用远程方法
*/
public static void main(String[] argv)
{
try
{
HelloInterface hello = (HelloInterface) Naming.lookup("Hello");
//如果要从另一台启动了RMI注册服务的机器上查找hello实例
//HelloInterface hello = (HelloInterface)Naming.lookup("//192.168.1.105:1099/Hello");
//调用远程方法
System.out.println(hello.say());
}
catch (Exception e)
{
System.out.println("HelloClient exception: " + e);
}
}
}