Java 简单的rpc 一
一,简单rpc 是基于Java socket 编程
ServerSocket serverSocket = new ServerSocket(9999); System.out.println("服务开启"); while(true) { //开启一个服务监听 Socket socket = serverSocket.accept(); System.out.println(socket.getInetAddress()+"-connected"); InputStream in = socket.getInputStream(); byte[] buf = new byte[1024]; in.read(buf);
//拿到序列化得数据 byte[] formatDate = formatData(buf); OutputStream out = socket.getOutputStream(); out.write(formatDate); socket.close();
}
通过NetModel类保证从客户端传入的参数 包括 类的名称 方法名称 参数类型 参数
package org.Simple.API; import java.io.Serializable; import java.util.Arrays; public class NetModel implements Serializable{ private static final long serialVersionUID = 1L; private String className; private String method; private Object[] args ; private String[] types; public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } public String getMethod() { return method; } public void setMethod(String method) { this.method = method; } public Object[] getArgs() { return args; } public void setArgs(Object[] args) { this.args = args; } public String[] getTypes() { return types; } public void setTypes(String[] types) { this.types = types; } @Override public String toString() { return "NetModel [className=" + className + ", method=" + method + ", args=" + Arrays.toString(args) + ", types=" + Arrays.toString(types) + "]"; } }
通过Java 反射 调用方法生成结果 在通过 serversocket 返回给客户端
try { //将收到的byte数组反序列化为NetModel类型,然后通过反射调用HelloServiceImpl实现类的方法 NetModel netModel = (NetModel)SerializeUtils.deSerialize(bs); //包点类名称 String className = netModel.getClassName(); //参数类型 String[] types = netModel.getTypes(); //参数 Object[] args = netModel.getArgs(); /*这里简单通过Map来做接口映射到实现类,从map中取 Map<String, String> map = new HashMap<String,String>(); map.put("org.Simple.API.HelloService", "org.Simple.S.HelloServiceImpl"); Class<?> clazz = Class.forName(map.get(className)); */ //也可以把这个键值放到配置文件下,通过配置文件读取 Class<?> clazz = Class.forName(getPropertyValue(className)); Class<?> [] typeClazzs = null; if(types!=null) { typeClazzs = new Class[types.length]; for (int i = 0; i < typeClazzs.length; i++) { typeClazzs[i] = Class.forName(types[i]); } } Method method = clazz.getMethod(netModel.getMethod(),typeClazzs); //方法调用 参数 Object object = method.invoke(clazz.newInstance(), args); byte[] byteArray = SerializeUtils.serialize(object); return byteArray; } catch (Exception e) { e.printStackTrace(); } return null;