RPC是指遠程過程調用,直觀說法就是A經過網絡調用B的過程方法。java
也就是說兩臺serverA。B,一個應用部署在Aserver上,想要調用Bserver上應用提供的函數/方法,由於不在一個內存空間,不能直接調用。需要經過網絡來表達調用的語義和傳達調用的數據。markdown
爲何RPC呢?就是沒法在一個進程內,甚至一個計算機內經過本地調用的方式完畢的需求,比方比方不一樣的系統間的通信,甚至不一樣的組織間的通信。由於計算能力需要橫向擴展。需要在多臺機器組成的集羣上部署應用網絡
RpcFramework框架
socket
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 */
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() {//對每一個請求new一個線程,匿名類
@Override
public void run() {
try {
try {
ObjectInputStream input = new ObjectInputStream(socket.getInputStream());
try {
String methodName = input.readUTF();
Class<?>[] parameterTypes = (Class<?>[]) input.readObject();
Object[] arguments = (Object[]) input.readObject();
ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());//接收client傳來的方法名、參數類型、參數
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 * server主機名 * @param port * server端口 * @return 遠程服務 * @throws Exception */
@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() {//用動態代理的方法進行包裝,看起來是在調用一個方法,事實上在內部經過socket通訊傳到server。並接收執行結果 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(); } } }); } }
RpcProvideride
public class RpcProvider {
public static void main(String[] args) throws Exception {
HelloService service = new HelloServiceImpl();
RpcFramework.export(service, 1234);
}
}
RpcConsumer 函數
public class RpcConsumer {
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);
}
}
}