标签:
远程过程:java进程.即一个java进程调用另外一个java进程中对象的方法.
调用方称作客户端(client),被调用方称作服务端(server).rpc的通信在java中表现为客户端去调用服务端对象中的方法.RPC通信就是cs结构的通信.client端会知道服务端被调用对象的接口.
RPC是hadoop分布式机制运行的基础.
接口:MyBizable
public interface MyBizable extends VersionedProtocol{ public static final int PORT = 123456 ; public abstract String hello(String name); public abstract long getProtocolVersion(String protocol,long clientVersion)throws IOException; }
接口对应的实现类:MyBiz
public class MyBiz implements MyBizable { @Override public long getProtocolVersion(String protocol, long clientVersion) throws IOException { return MyBizable.PORT; } @Override public String hello(String name) { System.out.println("我被调用了."); return "hello "+ name; } }
服务类:MyServer
public class MyServer { public static final String ADDRESS = "localhost"; public static final int PORT = 2454; public static void main(String[] args) throws Exception{ /** * 构造一个RPC的服务端 * @param instance 实例对象的方法会被客户端调用。 * @param bindAddress 监听绑定的地址 * @param port 监听连接的端口 * @param conf 配置 */ Server server = RPC.getServer(new MyBiz(), MyServer.ADDRESS, MyServer.PORT, new Configuration()); server.start(); } }
客户端:MyClient
public class MyClient { public static void main(String[] args) throws Exception{ MyBizable client =
(MyBizable) RPC.getProxy(MyBizable.class, MyBizable.PORT, new InetSocketAddress(MyServer.ADDRESS,MyServer.PORT), new Configuration()); String result = client.hello("world"); System.out.println(result); } }
标签:
原文地址:http://www.cnblogs.com/xiaolong1032/p/4401110.html