RMI:远程方法调用(Remote Method Invocation)
package rmi.com.jidondcloud.service;
import java.rmi.Remote;
import java.rmi.RemoteException;
/**
* Remote发布服务硬性要求,需要继承这个接口
*/
public interface IhelloService extends Remote {
String sayHello(String msg) throws RemoteException;
}
package rmi.com.jidondcloud.service;
import java.rmi.RemoteException;
import java.rmi.server.RMIClientSocketFactory;
import java.rmi.server.RMIServerSocketFactory;
import java.rmi.server.UnicastRemoteObject;
/**
* 发布服务硬性要求 :需要继承这个 UnicastRemoteObject类
*/
public class HeslloSerrviceImpl extends UnicastRemoteObject implements IhelloService {
public HeslloSerrviceImpl() throws RemoteException {
super();
}
public String sayHello (String msg)throws RemoteException {
return "hello," +msg;
}
}
服务端:
package rmi.com.jidondcloud.service;
import java.rmi.Naming;
import java.rmi.registry.LocateRegistry;
public class Server {
public static void main(String[] args) {
try{
//客户端要拿到 ihelloService 这个副本,然后去访问这个类方法,实现远程调用
//发布服务
IhelloService ihelloService=new HeslloSerrviceImpl();
//相当于注册中心,这个必须是1099端口
LocateRegistry.createRegistry(1099);
//绑定RMI协议,把ihelloService这个类带过去
Naming.rebind("rmi://127.0.0.1/hi",ihelloService);
//输出一句话证明服务启动成功
System.out.println("RMi服务端启动成功...");
}
catch (Exception e){
e.printStackTrace();
}
}
}
客户端:
package rmi.com.jidondcloud.client;
import rmi.com.jidondcloud.service.HeslloSerrviceImpl;
import rmi.com.jidondcloud.service.IhelloService;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
public class TestRmi {
public static void main(String[] args) throws RemoteException {
//本进程调用
/* IhelloService ihelloService=new HeslloSerrviceImpl();
String result = ihelloService.sayHello("robin");
System.out.println(result);*/
//下面是跨进程调用
//客户端从注册中心的地址中拿到一个代理类
try {
IhelloService ihelloService= (IhelloService) Naming.lookup("rmi://127.0.0.1/hi");
String result = ihelloService.sayHello("rmi-robin");
System.out.println(result);
} catch (NotBoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}