分布式架构探索 - 1. RPC框架之Java原生RMI

1. 什么是RPC

RPC(Remote Procedure Call)即远程过程调用,指的是不同机器间系统方法的调用,这和

同机器动态链接库(DLL)有点类似,只不过RPC是不同机器,通过网络通信来访问远程的资源。

 

2. Java RMI技术

RMI(Remote Method Invocation)即远程方法调用,是Java原生的RPC技术。

 * 使用了原生的序列化机制(序列化对象实现java.io.Serializable接口)

 * 底层通信基于BIO(Block IO)实现的Socket来完成

 * 性能较差 

 例子:

 2-1) 首先,定义远程对外服务接口

// 必须继承Remote接口
public interface HelloService extends Remote {
    String sayHello(String someOne) throws RemoteException;
}

 2-2) 远程接口的实现

// UnicastRemoteObject定义了服务调用方与提供方对象实例,并建立一对一连接
public class HelloServiceImpl extends UnicastRemoteObject implements HelloService {

    protected HelloServiceImpl() throws RemoteException {
        super();
    }

    @Override
    public String sayHello(String someOne) throws RemoteException {
        return "hello," + someOne;
    }
}

 2-3) 服务端远程服务启动

// 创建和注册服务
public class ServiceMain {
    public static void main(String[] args) throws Exception {
        LocateRegistry.createRegistry(8801);
        //指定通讯端口,防止被防火墙拦截
        RMISocketFactory.setSocketFactory(new CustomerSocketFactory());

        HelloService helloService = new HelloServiceImpl();
        Naming.bind("rmi://localhost:8801/helloService", helloService);
        System.out.println("ServiceMain provide RPC service now.");
    }
}
/**
 * 指定通讯端口,防止被防火墙拦截
 * Created by KG on 2017/3/8.
 */
public class CustomerSocketFactory extends RMISocketFactory {
    @Override
    public Socket createSocket(String host, int port) throws IOException {
        return new Socket(host, port);
    }

    @Override
    public ServerSocket createServerSocket(int port) throws IOException {
        if (port == 0) {
            port = 8501;
        }
        System.out.println("rmi notify port:" + port);
        return new ServerSocket(port);
    }
}

2-4) 客户端调用RMI服务

public class ClientMain {
    public static void main(String[] args) throws Exception {
        //服务引入
        HelloService helloService = (HelloService) Naming.lookup("rmi://localhost:8801/helloService");
        //调用远程方法
        System.out.println("RMI服务器返回的结果是 " + helloService.sayHello("Master HaKu"));
    }
}

 程序运行结果:

RMI服务器返回的结果是 hello,Master HaKu

 

posted @ 2018-03-14 10:53  Master HaKu  阅读(817)  评论(0编辑  收藏  举报