WritableRpcEngine是 Hadoop RPC 默认的实现。在 3.2.1 版本已经被标识为@Deprecated

定义接口协议

  1. /**
  2. * 协议接口
  3. */
  4. public interface ClicentNameNodeProtocol {
  5. //1. 定义协议的ID
  6. public static final long versionID = 1L;
  7. /**
  8. * 拿到元数据方法,协议通信前会访问元数据
  9. */
  10. public String getMetaData(String path);
  11. }

实现接口协议

  1. /**
  2. * 实现协议结构
  3. */
  4. public class ClicentNameNodeImpl implements ClicentNameNodeProtocol {
  5. public String getMetaData(String path) {
  6. // 数据存放的路径,有多少块,块大小,校验和,存储在哪一台机器上
  7. return path + ":3 - {BLOCK_1,BLOCK_2,BLOCK_3....";
  8. }
  9. }

创建Server服务, 注册协议,并启动RPC服务

  1. /**
  2. * 启动RPC服务
  3. */
  4. public class Server {
  5. public static void main(String[] args) throws IOException {
  6. //1. 构建RPC框架
  7. RPC.Builder builder = new RPC.Builder(new Configuration());
  8. //2. 绑定地址
  9. builder.setBindAddress("localhost");
  10. //3. 绑定端口
  11. builder.setPort(7777);
  12. //4. 绑定协议
  13. builder.setProtocol(ClicentNameNodeProtocol.class);
  14. //5. 调用协议实现类
  15. builder.setInstance(new ClicentNameNodeImpl());
  16. //6. 创建服务
  17. RPC.Server server = builder.build();
  18. //7. 启动服务
  19. server.start();
  20. }
  21. }

创建Client服务,请求数据接口

  1. /**
  2. * 访问RPC服务
  3. */
  4. public class Client {
  5. public static void main(String[] args) throws IOException {
  6. //1. 拿到RPC协议
  7. ClicentNameNodeProtocol proxy = RPC.getProxy(ClicentNameNodeProtocol.class, 1L,
  8. new InetSocketAddress("localhost", 7777), new Configuration());
  9. //2. 发送请求
  10. String metaData = proxy.getMetaData("/meta");
  11. //3. 打印元数据
  12. System.out.println(metaData);
  13. }
  14. }