JAVA原生RMI
步骤:
- 接口要继承java.rmi.Remote
- 方法要主动抛出RemoteException异常
- 实现类要继承 java.rmi.server.UnicastRemoteObject
- 防火墙设置 继承java.rmi.server.RMISocketFactory
接口
package com.ghgcn.rpc01.service;
import java.rmi.Remote;
import java.rmi.RemoteException;
/**
*
* @ClassName: HelloService
* @Description: 1.接口要继承java.rmi.Remote
* @author 刘楠
* @date 2018年7月9日 下午7:18:09
*
*/
public interface HelloService extends Remote{
/**
*
* @Title: sayHello
* @Description: 2.方法要主动抛出RemoteException异常
* @param @param someOne
* @param @return
* @param @throws RemoteException 设定文件
* @return String 返回类型
* @throws
*/
public String sayHello(String someOne) throws RemoteException;
}
实现
package com.ghgcn.rpc01.service.imp;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import com.ghgcn.rpc01.service.HelloService;
/**
*
* @ClassName: HelloServiceImp
* @Description: 3.实现类要继承 java.rmi.server.UnicastRemoteObject
* @author 刘楠
* @date 2018年7月9日 下午7:19:34
*
*/
public class HelloServiceImp extends UnicastRemoteObject implements HelloService {
/**
* @Fields serialVersionUID : TODO(用一句话描述这个变量表示什么)
*/
private static final long serialVersionUID = 4526949627605368404L;
public HelloServiceImp() throws RemoteException {
super();
}
public String sayHello(String someOne) throws RemoteException {
return "Hello "+someOne ;
}
}
注册服务与启动
public class ServerRun {
public static void main(String[] args) throws AlreadyBoundException, IOException {
//创建服务
HelloService helloService = new HelloServiceImp();
//注册服务
LocateRegistry.createRegistry(8801);
//绑定服务
Naming.bind("rmi://localhost:8801/helloService", helloService);
System.out.println("Servermain provide RPC Run now ");
}
}
主服务启动
- 创建服务
- 注册服务
- 添加防止防火墙拦截
- 绑定服务
客户端调用
public class ClientMain {
public static void main(String[] args) throws MalformedURLException, RemoteException, NotBoundException {
//服务引入
HelloService helloService = (HelloService) Naming.lookup("rmi://localhost:8801/helloService");
//调用
System.out.println("RMI服务调用:"+helloService.sayHello("张三"));
}
}
添加防止防火墙拦截
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);
}
}
主服务
public class ServerRun {
public static void main(String[] args) throws AlreadyBoundException, IOException {
//创建服务
HelloService helloService = new HelloServiceImp();
//注册服务
LocateRegistry.createRegistry(8801);
//防止防火墙拦截
RMISocketFactory.setSocketFactory(new CustomerSocketFactory());
//绑定服务
Naming.bind("rmi://localhost:8801/helloService", helloService);
System.out.println("Servermain provide RPC Run now ");
}
}