首先RMI(Remote Method Invocation)是Java特有的一种RPC实现,它能够使部署在不同主机上的Java对象进行通信与方法调用,它是一种基于Java的远程方法调用技术。
让我们优先来实现一个RMI的RPC案例吧。
项目源码地址: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"));
}
}
最后可以看看效果。