本博客 貓叔的博客,轉載請申明出處java
首先RMI(Remote Method Invocation)是Java特有的一種RPC實現,它可以使部署在不一樣主機上的Java對象進行通訊與方法調用,它是一種基於Java的遠程方法調用技術。git
讓咱們優先來實現一個RMI的RPC案例吧。github
項目源碼地址:RPC_Demo,記得是項目裏面的
comgithubrmi
架構
Remote
package com.github.rmi.server;
import java.rmi.Remote;
import java.rmi.RemoteException;
/** * Create by UncleCatMySelf in 21:03 2019\4\20 0020 */
public interface MyService extends Remote {
String say(String someOne)throws RemoteException;
}
複製代碼
package com.github.rmi.server;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
/** * Create by UncleCatMySelf in 21:05 2019\4\20 0020 */
public class MyServiceImpl extends UnicastRemoteObject implements MyService {
protected MyServiceImpl() throws RemoteException {
}
public String say(String someOne) throws RemoteException {
return someOne + ",Welcome to Study!";
}
}
複製代碼
package com.github.rmi.config;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.rmi.server.RMISocketFactory;
/** * Create by UncleCatMySelf in 21:15 2019\4\20 0020 */
public class CustomerSocketFactory extends RMISocketFactory {
public Socket createSocket(String host, int port) throws IOException {
return new Socket(host, port);
}
public ServerSocket createServerSocket(int port) throws IOException {
if (port == 0){
port = 8855;
}
System.out.println("RMI 通訊端口 : " + port);
return new ServerSocket(port);
}
}
複製代碼
package com.github.rmi.server;
import com.github.rmi.config.CustomerSocketFactory;
import java.rmi.Naming;
import java.rmi.registry.LocateRegistry;
import java.rmi.server.RMISocketFactory;
/** * Create by UncleCatMySelf in 21:07 2019\4\20 0020 */
public class ServerMain {
public static void main(String[] args) throws Exception {
//註冊服務
LocateRegistry.createRegistry(8866);
//指定通訊端口,防止被防火牆攔截
RMISocketFactory.setSocketFactory(new CustomerSocketFactory());
//建立服務
MyService myService = new MyServiceImpl();
Naming.bind("rmi://localhost:8866/myService",myService);
System.out.println("RMI 服務端啓動正常");
}
}
複製代碼
package com.github.rmi.client;
import com.github.rmi.server.MyService;
import java.rmi.Naming;
/** * Create by UncleCatMySelf in 21:10 2019\4\20 0020 */
public class ClientMain {
public static void main(String[] args) throws Exception {
//服務引入
MyService myService = (MyService) Naming.lookup("rmi://localhost:8866/myService");
//調用遠程方法
System.out.println("RMI 服務端調用返回:" + myService.say("MySelf"));
}
}
複製代碼
最後能夠看看效果。框架
學習交流羣:728698035性能
現架構設計(碼農)兼創業技術顧問,不羈平庸,熱愛開源,雜談程序人生與不按期乾貨。學習