使用hadoop RPC實現RPC呼叫
阿新 • • 發佈:2019-01-09
環境:
hadoop1.1.2
一、 定義服務提供的物件的介面, 此介面必須extends org.apache.hadoop.ipc.VersionedProtocol
eg.
import org.apache.hadoop.ipc.VersionedProtocol; /** * 業務介面, must extends VersionedProtocol * @author Administrator * */ public interface MyBiz extends VersionedProtocol{ // 業務方法 public abstract String hello(String name); }
二、定義服務提供的物件的介面實現類
eg.
import java.io.IOException; /** * 業務介面實現類 * @author Administrator * */ public class MyBizImpl implements MyBiz { static long VERSION = 123L; @Override public String hello(String name) { System.out.println("invoked here!"); return "hello " + name; } @Override public long getProtocolVersion(String protocol, long clientVersion) throws IOException { return VERSION; } }
三、 定義RPC Server端執行類
eg.
/** * RPC Server端 * @author Administrator * */ public class MyServer { // Server hostname static final String BIND_ADDRESS = "localhost"; // Server port static final int BIND_PORT = 12345; public static void main(String[] args) throws Exception { // 在指定的hostname和port提供業務介面實現物件服務 Server server = RPC.getServer( new MyBizImpl(), BIND_ADDRESS, BIND_PORT, new Configuration()); // 啟動服務 server.start(); } }
四、 定義RPC Client端執行類
eg.
/**
* RPC Client端
* @author Administrator
*
*/
public class MyClient {
public static void main(String[] args) throws Exception {
// 在指定的hostname和port獲取服務提供的業務介面代理物件
MyBiz proxy = (MyBiz)RPC.waitForProxy(
MyBiz.class, MyBizImpl.VERSION,
new InetSocketAddress(MyServer.BIND_ADDRESS, MyServer.BIND_PORT), new Configuration());
// 呼叫代理物件的業務方法
String v = proxy.hello("calvin");
System.out.println(v);
// 關閉代理物件
RPC.stopProxy(proxy);
}
}
五、說明
1. 服務端提供的物件的定義和執行在server端, 呼叫在client端
2. 服務端提供的物件必須是一個介面,並且extends VersioinedProtocal