1. 什麼是RPCjava
RPC(Remote Procedure Call)即遠程過程調用,指的是不一樣機器間系統方法的調用,這和服務器
同機器動態連接庫(DLL)有點相似,只不過RPC是不一樣機器,經過網絡通訊來訪問遠程的資源。網絡
2. Java RMI技術ide
RMI(Remote Method Invocation)即遠程方法調用,是Java原生的RPC技術。性能
* 使用了原生的序列化機制(序列化對象實現java.io.Serializable接口)spa
* 底層通訊基於BIO(Block IO)實現的Socket來完成code
* 性能較差 對象
例子:blog
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