Java:简单的RMI

来源:互联网 发布:python 爬虫框架 编辑:程序博客网 时间:2024/06/05 07:29

RMI(remote method invoke):远程方法调用。JVM允许从一台电脑的中调用另一台电脑的对象。

先实现个简单的。
定义服务端的接口

public interface Interface extends Remote {    public int add(int a, int b) throws Exception;}

接口一定要继承自Remote,然后实现该接口。

public class InterfaceImpl extends UnicastRemoteObject implements Interface {    public InterfaceImpl() throws RemoteException {    }    @Override    public int add(int a, int b) {        return a + b;    }    public static void main(String[] args) throws Exception {        // 这里一定要注册8080端口        LocateRegistry.createRegistry(8080);        // 可以通过rmi://localhost:8080/impl获得那个接口        Naming.bind("rmi://localhost:8080/impl", new InterfaceImpl());    }}

客户端调用:

public class Client {    public static void main(String[] args) throws Exception {        Interface impl = (Interface) Naming.lookup("rmi://localhost:8080/impl");        System.out.println(impl.add(1, 2));    }}

这是一个非常简单远程接口调用的实现。