一、需求
完成一个类似的RPC函数:
// 要求:输入你的真实学号,返回你的真实姓名
// 输入学号20210000000000,返回null
// 输入学号20210123456789,返回心心
// 作业上缴:截图server端和client端的执行结果 String findName(int studentId);
二、分析
其实就是模拟 RPC 的客户端、服务端、通信协议三者如何工作的
来自网络截图,右图的服务端代理调用改为:findName方法,原理是一模一样的。
三、代码编写
3.1 创建RPC协议
RPCProtocol类
public interface RPCProtocol {
long versionID = 666;
// void mkdirs(String path);
void findNamde(long studentId);
}
3.2 创建RPC服务端
// 实现通信接口
public class NNServer implements RPCProtocol{
private static Map<Long,String> cache = new HashMap<>();
static {
cache.put(20210123456789l,"心心");
}
public static void main(String[] args) throws IOException {
// 启动服务
RPC.Server server = new RPC.Builder(new Configuration())
.setBindAddress("localhost")
.setPort(8888)
.setProtocol(RPCProtocol.class)
.setInstance(new NNServer())
.build();
System.out.println("服务器器开始工作");
server.start();
}
/**
* 实现一个查询名字的功能
* @param studentId
*/
@Override
public void findNamde(long studentId) {
String resName = cache.get(studentId);
System.out.println("服务器返回结果:" + resName);
}
// @Override
// public void mkdirs(String path) {
// System.out.println("服务器接收到了客户端请求" + path);
// }
}
3.3 创建RPC客户端
public class HDFSClient {
public static void main(String[] args) throws IOException {
// 获取客户端对象
RPCProtocol client = RPC.getProxy(RPCProtocol.class, RPCProtocol.versionID, new InetSocketAddress("localhost", 8888),
new Configuration());
System.out.println("客户端开始工作");
// client.mkdirs("/input");
//
long studentId = 20210000000000l;
System.out.println("客户端输入 查询参数:" + studentId );
client.findNamde(studentId);
}
}
3.4结果
client
server端
git地址后面补上