天天看點

java分布式架構rmi_分布式架構探索 - 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 extendsRemote {

String sayHello(String someOne)throwsRemoteException;

}

2-2) 遠端接口的實作

//UnicastRemoteObject定義了服務調用方與提供方對象執行個體,并建立一對一連接配接

public class HelloServiceImpl extends UnicastRemoteObject implementsHelloService {protected HelloServiceImpl() throwsRemoteException {super();

}

@Overridepublic String sayHello(String someOne) throwsRemoteException {return "hello," +someOne;

}

}

2-3) 服務端遠端服務啟動

//建立和注冊服務

public classServiceMain {public static void main(String[] args) throwsException {

LocateRegistry.createRegistry(8801);//指定通訊端口,防止被防火牆攔截

RMISocketFactory.setSocketFactory(newCustomerSocketFactory());

HelloService helloService= newHelloServiceImpl();

Naming.bind("rmi://localhost:8801/helloService", helloService);

System.out.println("ServiceMain provide RPC service now.");

}

}

public class CustomerSocketFactory extendsRMISocketFactory {

@Overridepublic Socket createSocket(String host, int port) throwsIOException {return newSocket(host, port);

}

@Overridepublic ServerSocket createServerSocket(int port) throwsIOException {if (port == 0) {

port= 8501;

}

System.out.println("rmi notify port:" +port);return newServerSocket(port);

}

}

2-4) 用戶端調用RMI服務

public classClientMain {public static void main(String[] args) throwsException {//服務引入

HelloService helloService = (HelloService) Naming.lookup("rmi://localhost:8801/helloService");//調用遠端方法

System.out.println("RMI伺服器傳回的結果是 " + helloService.sayHello("Master HaKu"));

}

}

程式運作結果:

RMI伺服器傳回的結果是 hello,Master HaKu