本文發表于本人博客。
????上次寫了個hadoop偽分布環境搭建的筆記了,今天來說下hadoop分布式構建的基礎RPC,這個RPC在提交Job任務的時候底層就是創建了RPC來實現遠程過程調用服務端。
????我們首先可以通過Job的waitForCompletion(boolean verbose)方法來跟蹤代碼,按照順序往下查看源碼,在JobClient中發現了:
this.rpcJobSubmitClient = createRPCProxy(JobTracker.getAddress(conf), conf);this.jobSubmitClient = createProxy(this.rpcJobSubmitClient, conf);
我們可以發現createProxy()方法返回的是JobSubmissionProtocol接口,而這個接口實際上繼承VersionedProtocol接口,可以查看這個接口的說明:
/*** Superclass of all protocols that use Hadoop RPC.* Subclasses of this interface are also supposed to have* a static final long versionID field.*/
可以看到是所有hadoopRPC的協議超類。那我們來使用這個接口實現在server以及client中RPC。看下面代碼:
conf文件類:
/*** RPC 配置* @author Administrator**/
public class conf {public static final String ADDR = "localhost";public static final int PORT = 9000;public static final long version = 123456L;
}
Operator文件類:
interface OperatorAble extends VersionedProtocol {/*** 說話* @param name* @return*/public String Talk(String name);
}
public class Operator implements OperatorAble {/*** 說話* @param name* @return*/@Overridepublic String Talk(String name){System.out.println("Operator is call......");return "hello:" + name;}@Overridepublic long getProtocolVersion(String protocol, long clientVersion) throws IOException{return conf.version;}
}
Server文件類:
/*** RPC 服務端* @author Administrator**/
public class Server {public static void main(String[] args) throws Exception {org.apache.hadoop.ipc.RPC.Server server = RPC.getServer(new Operator(), conf.ADDR, conf.PORT, new Configuration());server.start();}
}
Client文件類:
/*** RPC 客戶端* @author Administrator**/
public class Client {public static void main(String[] args) throws Exception {OperatorAble proxy = (OperatorAble)RPC.waitForProxy(OperatorAble.class, conf.version, new InetSocketAddress(conf.ADDR, conf.PORT), new Configuration());for (int i = 0; i < 100000; i++) {String talk = proxy.Talk("luoliang.me");System.out.println(talk);}RPC.stopProxy(proxy);}}
這里特別需要注意一下的就是實現VersionedProtocol接口的時候,如果直接實現這個接口那么我可以想想在客戶端怎么來通過接口調用啊,而這個VersionedProtocol接口是沒有我們需要的功能,那只有重新創建一個OperatorAble接口再繼承次VersionedProtocol接口了,在客戶端那邊使用OperatorAble來遠程過程調用!當執行
String talk = proxy.Talk("luoliang.me");
時,在服務端就會輸出
Operator is call......
這樣表示服務端已經調用了!大家可以按照剛才的思路跟蹤下去看看他們是怎么做的,這里就不說了。
這次先到這里。堅持記錄點點滴滴!