hadooprpc
(1)定义接口
原因:动态代理可以提供对另一个对象的访问,同时隐藏实际对象的具体事实,代理对象对客户隐藏了实际对象。目前Java开发包中提供了对动态代理的支持,但现在
只支持对
接口
的实现
。
(2)反射——动态加载类
(3)序列化
(4)
非阻塞的异步IO
(NIO)
1
package
cn.jon.hadoop.rpc;
2
3
public
interface
MyBizable {
4
long
versionID = 123456;
//该字段必须要有,不然会报java.lang.NoSuchFieldException: versionID异常
5
public
String doSomething(String str);
6
}
服务端RPCServer实现MyBizable接口并绑定IP地址及端口号:
package
cn.jon.hadoop.rpc;
import
org.apache.hadoop.conf.Configuration;
import
org.apache.hadoop.ipc.RPC;
import
org.apache.hadoop.ipc.Server;
public
class
RPCServer
implements
MyBizable {
@Override
public
String doSomething(String str) {
return
str; }
/** *
@param
args
*
@throws
Exception
*
@throws
*/
public
static
void
main(String[] args)
throws
Exception {
Server server =
new
RPC.Builder(
new
Configuration())
.setProtocol(MyBizable.
class
)
.setInstance(
new
RPCServer())
.setBindAddress("192.168.8.100")
.setPort(8077)
.build();
server.start(); }}
客户端RPCClient:
package
cn.jon.hadoop.rpc;
import
java.net.InetSocketAddress;
import
org.apache.hadoop.conf.Configuration;
import
org.apache.hadoop.ipc.RPC;
public
class
RPCClient {
/** *
@param
args
*
@throws
Exception */
public
static
void
main(String[] args)
throws
Exception {
// TODO Auto-generated method stub
MyBizable proxy = RPC.getProxy(MyBizable.
class
, 123456,
new
InetSocketAddress("192.168.8.100", 8077) ,
new
Configuration());
String result = proxy.doSomething("服务端");
System.out.println(result);
RPC.stopProxy(proxy);
}
}