標籤:blog http java 檔案 2014 os
1.1. hadoop遠端程序呼叫
1、 遠程介面調用(必須實現VersionedProtocol介面)
裡面有一個方法,IPC通訊時會比較用戶端和服務端介面的版本號碼。必須一致才可以
package rpc;import org.apache.hadoop.ipc.VersionedProtocol;public interface MyBizable extends VersionedProtocol {//必須具有一個版本號碼public static final long VERSION = 100L;//實際調用方法public abstract String hello(String name);}
2、 定義遠程對象的實作類別
package rpc;import java.io.IOException;public class MyBiz implements MyBizable{//擷取版本號碼@Overridepublic long getProtocolVersion(String protocol, long clientVersion)throws IOException {// TODO Auto-generated method stubreturn VERSION;}@Overridepublic String hello(String name){System.out.println("我被調用了");return "hello:" + name;}}
3、 構建伺服器
package rpc;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.ipc.RPC;
import org.apache.hadoop.ipc.RPC.Server;
public class MyServer {
public static final String SERVER_ADDRESS = "localhost";
public static final int SERVER_PORT = 12344;
public static void main(String[] args) throws Exception {
//public static Server getServer(final Object instance, final String bindAddress, final int port, Configuration conf)
/** Construct an RPC server.
* @param instance the instance whose methods will be called用戶端調用遠程介面
* @param bindAddress the address to bind on to listen for connection監聽串連地址
* @param port the port to listen for connections on連接埠
* @param conf 設定檔
*/
final Server server = RPC.getServer(new MyBiz(), SERVER_ADDRESS, SERVER_PORT, new Configuration());
server.start();
}
}
4、用戶端實現
package rpc;import java.io.IOException;import java.net.InetSocketAddress;import org.apache.hadoop.conf.Configuration;import org.apache.hadoop.ipc.RPC;import org.apache.hadoop.ipc.VersionedProtocol;public class MyClient {public static void main(String[] args) throws Exception {/** Construct a client-side proxy object that implements the named protocol, * talking to a server at the named address. */final MyBizable proxy = (MyBizable) RPC.waitForProxy(MyBizable.class
, MyBizable.VERSION
, new InetSocketAddress(MyServer.SERVER_ADDRESS, MyServer.SERVER_PORT)
, new Configuration());//普通測試String result = proxy.hello("hello");System.out.println(result);RPC.stopProxy(proxy);}}
原理:(暫且不關注,在需要的時候可以再複習)
總結:hadoop的namenode,secondarynamenode,datanode,jobtrack等進程都實現了遠程調用介面,也就是說他們每一個都是一個服務端Server,等待用戶端的調用。相互之間彼此充當用戶端和服務端的角色。
啟動hadoop實際上就是啟動了RPC的Server。