远程服务调用,可以在client端运行server端的java代码
server
package rmi.demo;
import java.rmi.NoSuchObjectException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
public class RmiServer {
public static void main(String[] args) throws Exception {
System.out.println("server");
int port = 8090;
RemoteObject object = new RemoteObjectImpl();
RemoteObject remoObject = (RemoteObject) UnicastRemoteObject.exportObject(object, 0); //导入对象,导入RemoteObjectImpl对象会报错 无法转换
Registry serRegistry = LocateRegistry.createRegistry(port); //启动rmi server
serRegistry.bind("remoteObject", remoObject);
new Thread(()->{
try {
Thread.sleep(10 * 1000);
UnicastRemoteObject.unexportObject(object, true); //把对象导出,当没有对象时,关闭rmi server端
System.out.println("rmi close");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchObjectException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}).start();
}
}
cilent
package rmi.demo;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class RmiClient {
public static void main(String[] args) throws Exception {
System.out.println("client");
Registry registry = LocateRegistry.getRegistry("127.0.0.1",8090); //获取远程rmi server
RemoteObject remoteObject = (RemoteObject) registry.lookup("remoteObject"); //获取对象
remoteObject.run(); //调用远程的对象
}
}
object
package rmi.demo;
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface RemoteObject extends Remote{
void run() throws RemoteException;
}
package rmi.demo;
import java.rmi.RemoteException;
public class RemoteObjectImpl implements RemoteObject{
@Override
public void run() throws RemoteException {
System.out.println("RemoteObjectImpl");
}
}