本博客 猫叔的博客,转载请申明出处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性能
现架构设计(码农)兼创业技术顾问,不羁平庸,热爱开源,杂谈程序人生与不按期干货。学习