【Java】RMI

1. 什么是RMI

RMI(Remote Method Invocation,远程方法调用)是用Java在JDK1.2中实现的,它大大增强了Java开发分布式应用的能力。
【Java】RMI_第1张图片

2. 代码

公共代码

先定义一个接口去继承Remote接口,这样RMI可以将实现该接口点的对象向客户端传输:

import java.rmi.Remote;
import java.rmi.RemoteException;

public interface RemoteHelloWord extends Remote {
    String sayHello() throws RemoteException;
}

实现这个接口:

import java.rmi.RemoteException;

public class RemoteHelloWordImpl implements RemoteHelloWord {
    @Override
    public String sayHello() throws RemoteException {
        return "Hello Word!";
    }
}

服务端

import java.rmi.AlreadyBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;

public class RMIServer {
    public static void main(String[] args) {
        try {
            RemoteHelloWord hello=new RemoteHelloWordImpl();
            // 负责导出我们定义好的远程对象,并用任意一个tcp端口来接收远程方法调用
            // 同时它还会返回一个存根stub,stub会被发送给client端进行调用
            RemoteHelloWord stub=(RemoteHelloWord)UnicastRemoteObject.exportObject(hello, 9999);
            // registry端口 1099
            LocateRegistry.createRegistry(1099);
            // 获取registry
            Registry registry=LocateRegistry.getRegistry();
            // 将stub命名,并注册到registry上
            registry.bind("helloword", stub);
        } catch (RemoteException | AlreadyBoundException e) {
            e.printStackTrace();
        }
    }
}

客户端

import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

public class RMIClient {
    public static void main(String[] args) {
        try {
        	// 获取指定host上的registry 
            Registry registry = LocateRegistry.getRegistry( "localhost" );
            // 根据名字查找对应的stub
            RemoteHelloWord hello = (RemoteHelloWord) registry.lookup( "helloword" );
            // 执行方法
            String ret = hello.sayHello();
            System.out.println( ret );
        } catch (RemoteException | NotBoundException e) {
            e.printStackTrace();
        }
    }
}

你可能感兴趣的:(Java)