使用hadoop RPC实现RPC调用

1 篇文章 0 订阅

环境:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值