一,簡單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;