最近在看设计模式《Head First》,其中有个代理模式,给我的案例是一个远程代理的例子,这个例子是使用RMI技术写的,我原本都木有听过RMI是什么,所以这里做一个RMI的记录,并且来解释一下是什么东西。
我们先来了解一下事情,那就是我们在两个JVM虚拟机之间进行远程的方法调用。
一个接口:
package com.againfly.rmi.server; import java.rmi.Remote; import java.rmi.RemoteException; public interface MyRemote extends Remote{ public String sayHello() throws RemoteException; public void selfRun(String msg) throws RemoteException; }
实现这个Remote接口:
package com.againfly.rmi.server; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; public class MyRemoteImpl extends UnicastRemoteObject implements MyRemote{ protected MyRemoteImpl() throws RemoteException {} @Override public String sayHello() throws RemoteException { return "Server says, 'Hey'"; } @Override public void selfRun(String msg) throws RemoteException { System.out.println("Client传递内容:" + msg); } }
这里我们需要注意一下,这里的返回值是String和void,当我们要实现远程操作的时候,返回类型是必须实现了序列化(Serializable)接口的。
来运行服务端主方法:
package com.againfly.rmi.server; import java.net.MalformedURLException; import java.rmi.Naming; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; public class Main { public static void main(String[] args) { try { MyRemote server = new MyRemoteImpl(); LocateRegistry.createRegistry(8888); Naming.rebind("rmi://localhost:8888/RemoteHello", server); System.out.println(">>>>>INFO:远程RemoteHello对象绑定成功!"); } catch (RemoteException e) { System.out.println("创建远程对象发生异常!"); e.printStackTrace(); } catch (MalformedURLException e) { System.out.println("发生URL畸形异常!"); e.printStackTrace(); } } }
==========================================================
好的,到了这里,服务端已经开始运行,等待客户端的接入并操作了。
>>>>>INFO:远程RemoteHello对象绑定成功!
现在来看看客户端,客户端很简单:
package com.againfly.rmi.client; import java.rmi.Naming; import com.againfly.rmi.server.MyRemote; public class MyRemoteClient { public static void main(String[] args) { try{ MyRemote service = (MyRemote) Naming.lookup("rmi://192.168.1.40:8888/RemoteHello"); String s = service.sayHello(); System.out.println("client:>>> " + s); service.selfRun("Test 消息"); }catch(Exception e){ e.printStackTrace(); } } }
当我们在保证服务端开启的情况下来运行客户端来看下服务端和客户端之间的控制台窗口
>>>>>INFO:远程RemoteHello对象绑定成功! Client传递内容:Test 消息
client:>>> Server says, 'Hey'
最新评论