Hadoop RPC简单实例

1、导入Hadoop-Common-2.6.0.jar导入工程,里面的IPC实现RPC需要的文件。

2、服务器端

 (1)服务接口
package com.neu.rpc.server;

/**
 * Created by apple on 16/6/26.
 */
public interface LoginServiceInterface {
    public static final long versionID = 1L;

    public String login(String username, String password);
}

(2)服务实现

package com.neu.rpc.server;


/**
 * Created by apple on 16/6/26.
 */
public class LoginServiceImpl implements LoginServiceInterface {
    @Override
    public String login(String username, String password) {
        return username + " login success";
    }
}

(3)RPC服务端,将上述服务进行发布,监控RPC客户端发来的请求

package com.neu.rpc.server;

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

import java.io.IOException;

/**
 * Created by apple on 16/6/26.
 */
public class Starter {
    public static void main(String[] args) throws IOException {
        RPC.Builder build = new RPC.Builder(new Configuration());
        build.setBindAddress("localhost").setPort(10000).setProtocol(LoginServiceInterface.class).setInstance(new LoginServiceImpl());
        RPC.Server server = build.build();
        server.start();
    }
}

 

3、客户端

 (1)RPC服务接口【问题:因为服务协议是包名加类名,因此客户端的服务接口的包名要与服务端接口的包名一致
package com.neu.rpc.server;

/**
 * Created by apple on 16/6/26.
 */
public interface LoginServiceInterface {
    public static final long versionID = 1L;

    public String login(String username, String password);
}

(2)RPC客户端请求服务

public class LoginController {
    public static void main(String[] args) throws IOException {
        LoginServiceInterface proxy= RPC.getProxy(LoginServiceInterface.class,1L,new InetSocketAddress("localhost",10000),new Configuration());
        String msg=proxy.login("xiaoming","123123");
        System.out.println(msg);
    }
}

4、实验结果

com.intellij.rt.execution.application.AppMain com.neu.rpc.client.LoginController
2016-06-28 00:23:36,542 WARN  [main] util.NativeCodeLoader (NativeCodeLoader.java:<clinit>(62)) - Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
xiaoming login success

Process finished with exit code 0

  

 

posted @ 2016-06-28 00:22  z.arbitrary  阅读(738)  评论(0编辑  收藏  举报