实现java RPC框架
生活随笔
收集整理的這篇文章主要介紹了
实现java RPC框架
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
http://javatar.iteye.com/blog/1123915
主要利用socket通信,反射,代理實現類似RMI的RPC框架
首先是框架的代碼
package framework;import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.net.ServerSocket; import java.net.Socket;/*** RpcFramework* * @author william.liangf*/ public class RpcFramework {/*** 暴露服務* * @param service 服務實現* @param port 服務端口* @throws Exception*/public static void export(final Object service, int port) throws Exception {if (service == null)throw new IllegalArgumentException("service instance == null");if (port <= 0 || port > 65535)throw new IllegalArgumentException("Invalid port " + port);System.out.println("Export service " + service.getClass().getName() + " on port " + port);ServerSocket server = new ServerSocket(port);for(;;) {try {final Socket socket = server.accept();//服務器端一旦收到消息,就創建一個線程進行處理new Thread(new Runnable() {@Overridepublic void run() {try {try {ObjectInputStream input = new ObjectInputStream(socket.getInputStream());try {String methodName = input.readUTF();//service是服務器端提供服務的對象,但是,要通過獲取到的調用方法的名稱,參數類型,以及參數來選擇對象的方法,并調用。獲得方法的名稱Class<?>[] parameterTypes = (Class<?>[])input.readObject();//獲得參數的類型Object[] arguments = (Object[])input.readObject();//獲得參數ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());try {Method method = service.getClass().getMethod(methodName, parameterTypes);//通過反射機制獲得方法Object result = method.invoke(service, arguments);//通過反射機制獲得類的方法,并調用這個方法output.writeObject(result);//將結果發送} catch (Throwable t) {output.writeObject(t);} finally {output.close();}} finally {input.close();}} finally {socket.close();}} catch (Exception e) {e.printStackTrace();}}}).start();} catch (Exception e) {e.printStackTrace();}}}/*** 引用服務* * @param <T> 接口泛型* @param interfaceClass 接口類型* @param host 服務器主機名* @param port 服務器端口* @return 遠程服務* @throws Exception*///原理是通過代理,獲得服務器端接口的一個“代理”的對象。對這個對象的所有操作都會調用invoke函數,在invoke函數中,是將被調用的函數名,參數列表和參數發送到服務器,并接收服務器處理的結果@SuppressWarnings("unchecked")public static <T> T refer(final Class<T> interfaceClass, final String host, final int port) throws Exception {if (interfaceClass == null)throw new IllegalArgumentException("Interface class == null");if (! interfaceClass.isInterface())throw new IllegalArgumentException("The " + interfaceClass.getName() + " must be interface class!");if (host == null || host.length() == 0)throw new IllegalArgumentException("Host == null!");if (port <= 0 || port > 65535)throw new IllegalArgumentException("Invalid port " + port);System.out.println("Get remote service " + interfaceClass.getName() + " from server " + host + ":" + port);return (T) Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class<?>[] {interfaceClass}, new InvocationHandler() {public Object invoke(Object proxy, Method method, Object[] arguments) throws Throwable {Socket socket = new Socket(host, port);try {ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());try {output.writeUTF(method.getName());output.writeObject(method.getParameterTypes());output.writeObject(arguments);ObjectInputStream input = new ObjectInputStream(socket.getInputStream());try {Object result = input.readObject();if (result instanceof Throwable) {throw (Throwable) result;}return result;} finally {input.close();}} finally {output.close();}} finally {socket.close();}}});}}服務接口 package user;public interface HelloService {String hello(String name); }
實現服務 package user;public class HelloServiceImpl implements HelloService{public String hello(String name) {return "Hello " + name;}}
服務器 package user; import framework.RpcFramework;public class Server {public static void main(String []args) throws Exception {HelloService service = new HelloServiceImpl();RpcFramework.export(service, 1234); } }
客戶機 package user; import framework.RpcFramework;public class Client {public static void main(String[] args) throws Exception { HelloService service = RpcFramework.refer(HelloService.class, "127.0.0.1", 1234); for (int i = 0; i < Integer.MAX_VALUE; i ++) { String hello = service.hello("World" + i); System.out.println(hello); Thread.sleep(1000); } } }
javac framework/RpcFramework.java?
javac -classpath . user/*.java
java -classpath . user.Server
java -classpath . user.Client
總結
以上是生活随笔為你收集整理的实现java RPC框架的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Erlang与java的内存架构比较
- 下一篇: Python学习笔记一:数据类型转换