RPC调用需要服务端和客户端使用相同的协议:
协议:
package cn.itcast.bigdata.hadooprpc.protocol; public interface IUserLoginService { public static final long versionID = 100L; public String login(String name,String passwd); }
这里协议就是接口
服务端的实现类:
package cn.itcast.bigdata.hadooprpc.service; import cn.itcast.bigdata.hadooprpc.protocol.IUserLoginService; public class UserLoginServiceImpl implements IUserLoginService{ @Override public String login(String name, String passwd) { return name + "logged in successfully..."; } }
发布服务:
package cn.itcast.bigdata.hadooprpc.service; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.ipc.RPC; import org.apache.hadoop.ipc.RPC.Builder; import org.apache.hadoop.ipc.RPC.Server; import cn.itcast.bigdata.hadooprpc.protocol.ClientNamenodeProtocol; import cn.itcast.bigdata.hadooprpc.protocol.IUserLoginService; public class PublishServiceUtil { public static void main(String[] args) throws Exception { Builder builder= new RPC.Builder(new Configuration()); builder.setBindAddress("localhost") .setPort(9999) .setProtocol(IUserLoginService.class) .setInstance(new UserLoginServiceImpl()); Server server= builder.build(); server.start(); } }
客户端调用RPC服务:
package cn.itcast.bigdata.hadooprpc.client; import java.net.InetSocketAddress; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.ipc.RPC; import cn.itcast.bigdata.hadooprpc.protocol.IUserLoginService; public class UserLoginAction { public static void main(String[] args) throws Exception { IUserLoginService userLoginService = RPC.getProxy(IUserLoginService.class, 100L, new InetSocketAddress("localhost", 9999), new Configuration()); String login = userLoginService.login("angelababy", "1314520"); System.out.println(login); } }
使用的hadoop的hadoop-common-2.6.4.jar这个j包,在其他工程也可以使用