hadoop学习笔记-prc通信原理

rpc(remote procedure call)

不同java进程间的对象方法调用

一方称作服务端(server),一方称作客户端(client)。

server端提供对象,供客户端调用,被调用的对象的方法的执行发生在server端。

rpc是hadoop框架运行的基础。

下面是一个基于hadoop的rpc框架的例子:

服务端代码:

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 = 12345;
	
	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception{
		/** 构造一个 RPC server.
	     * @param instance 实例中的方法会被客户端调用
	     * @param bindAddress 绑定的地址用于监听连接的到来
	     * @param port 绑定的这个端口用于监听连接的到来
	     * @param conf the configuration to use
	     */
		final Server server = RPC.getServer(new MyBiz(), SERVER_ADDRESS, SERVER_PORT, new Configuration());
		server.start();
	}

}
MyBiz类为真正被调用的类,它实现了MyBizable接口中定义的hello()方法, getProtocolVersion()方法在 MyBizable的父接口 VersionedProtocol中定义;
package rpc;

import java.io.IOException;

public class MyBiz implements MyBizable{
	/* (non-Javadoc)
	 * @see rpc.MyBizable#hello(java.lang.String)
	 */
	@Override
	public String hello(String name){
		System.out.println("我被调用了!");
		return "hello" + name;
	}

	@Override
	public long getProtocolVersion(String protocol, long clientVersion)
			throws IOException {
		return MyBizable.VERSION;
	}
}
 MyBizable继承 VersionedProtocol接口

 

 

package rpc;

import org.apache.hadoop.ipc.VersionedProtocol;

public interface MyBizable extends VersionedProtocol{
	public static final long VERSION = 2345345234L;
	public abstract String hello(String name);

}
 

 

 下面是客户端代码:

package rpc;

import java.net.InetSocketAddress;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.ipc.RPC;

public class MyClient {

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception{
		/** 构造一个客户端的代理对象。 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()
			      );
		final String result = proxy.hello("world");
		System.out.println("客户端调用结果"+result);
		
		RPC.stopProxy(proxy);
	}

}

 启动服务端:



 执行客户端,输出:



 服务端输出:



 

总结:

1. 服务端提供的对象必须是一个接口,接口extends VersioinedProtocal

2. 客户端能够调用的对象中的方法必须位于对象的接口中

FileSystem与Namenode通过rpc通信过程,如图:

 

猜你喜欢

转载自yehao0716.iteye.com/blog/2023784