RMI简介

RMI实现RPC

RMI(Remote Method Invocation)远程方法调用,RMI是从JDK1.2推出的功能,可以实现在一个Java应用中调用本地方法一样调用另一个服务器中Java的内容

执行流程

API介绍

Remote,java.rmi.Remote定义了此接口为远程调用接口,若接口被外部调用,需要继承此接口

public interface Remote()

RemoteException

java.rmi.RemoteException,继承了Remote接口的接口中,如果方法允许被远程调用,需要抛出此异常

UnicastRemoteObject

java.rmi.server.UnicastRemoteObject,实现了Remote接口和Serializable接口

自定义接口实现类除了实现自定义接口还需要继承此类

locateRegistry

java.rmi.reegistry.LocateRegistry

可以通过LocateRegistry在本机上创建Registry,通过特定端口就可以访问这个Registry

Naming

java.rmi.Naming

Naming定义了发布内容可访问RMI名称,也是通过Naming获取到指定的远程方法

代码实现

接口类

public interface DemoService extends Remote{
    String demo(String param) throws RemoteException;
}

接口实现类、服务端和客户端

public class DemoServiceImpl extends UnicastRemoteObject implements DemoService{    
    public DemoServiceImpl() throws RemoteException{

    }    

    public String demo(String param) throws RemoteException{
        return param + "abc";
    }
}

public class DemoServer{
    public static void main(String[] args){
        try{
            // 创建接口实例
            DemoServie demoService = new DemoServiceImpl();
            // 创建注册表
            LocateRegistry.createRegistry(8989);
            // 绑定服务
            Naming.bind("rmi://localhost:8989/demoService", demoService);
            System.out.println("绑定服务成功!");
        }catch(RemoteException e){
            e.printStackTrace();
        }catch(AlreadyBoundException e){
            e.printStackTrace();
        }catch(MalformedURLException e){
            e.printStackTrace();
        }
    }    
}

public class ClientDemo{
    public static void main(String[] args){
        try{
            Remote lookup = Naming.lookup("rmi://localhost:8989/demoService");
            String result = demoService.demo("test");
            System.out.println(result);
        }catch(RemoteException e){
            e.printStackTrace();
        }catch(AlreadyBoundException e){
            e.printStackTrace();
        }catch(MalformedURLException e){
            e.printStackTrace();
        }        
    }
}

 

论读书
睁开眼,书在面前
闭上眼,书在心里
原文地址:https://www.cnblogs.com/YC-L/p/14357635.html