从零手写RPC
RPC概述
RPC(Remote Proceduce Call 遠(yuǎn)程過程調(diào)用) 一般用來實(shí)現(xiàn)部署在不同機(jī)器上的系統(tǒng)之間的方法調(diào)用,使程序能夠像訪問本地系統(tǒng)資源一樣,通過網(wǎng)絡(luò)傳輸過去訪問遠(yuǎn)端系統(tǒng)資源。
RPC 調(diào)用過程
Stub 主要作用
* 序列化:負(fù)責(zé)數(shù)據(jù)的序列化發(fā)序列化。
* 網(wǎng)絡(luò)傳輸:數(shù)據(jù)發(fā)送與接收。
注:ServerStub又叫Skeleton。
RPC 實(shí)現(xiàn)
1. 遠(yuǎn)程服務(wù)接口
public interface IHello {public String sayHello(String info); }2. 遠(yuǎn)程服務(wù)接口實(shí)現(xiàn)類(Server)
public class HelloService implements IHello {public String sayHello(String info) {String result = "hello : " + info;System.out.println(result);return result;} }提供服務(wù)實(shí)現(xiàn)的類。
3.服務(wù)器代理實(shí)現(xiàn)(Skeleton)
public class RpcProxyServer {private IHello hello = new HelloService();public void publisherServer(int port) {try (ServerSocket ss = new ServerSocket(port)) {while (true) {try (Socket socket = ss.accept()) {try (ObjectInputStream ois = new ObjectInputStream(socket.getInputStream())) {String method = ois.readUTF();Object[] objs = (Object[]) ois.readObject();Class<?>[] types = new Class[objs.length];for (int i = 0; i < types.length; i++) {types[i] = objs[i].getClass();}Method m = HelloService.class.getMethod(method, types);Object obj = m.invoke(hello, objs);try (ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream())) {oos.writeObject(obj);oos.flush();}}} catch (Exception e) {e.printStackTrace();}}} catch (Exception e) {e.printStackTrace();}} }4. RPC 客戶端代理實(shí)現(xiàn)(ClientStub)
public class RpcProxyClient<T> {public T proxyClient(Class<T> clazz) {return (T) clazz.cast(Proxy.newProxyInstance(clazz.getClassLoader(), clazz.getInterfaces(), new InvocationHandler() {@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {try (Socket socket = new Socket("localhost", 8000)) {try (ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream())) {oos.writeUTF(method.getName());oos.writeObject(args);oos.flush();try (ObjectInputStream ois = new ObjectInputStream(socket.getInputStream())) {return ois.readObject();}}}}}));} }5.服務(wù)端發(fā)布服務(wù)
public class RpcServer {//發(fā)布服務(wù)public static void main(String[] args) {RpcProxyServer server = new RpcProxyServer();server.publisherServer(8000);} }6.客戶端調(diào)用(Client)
public class RpcClient {// 調(diào)用服務(wù)public static void main(String[] args) {RpcProxyClient<HelloService> rpcClient = new RpcProxyClient<>();IHello hello = rpcClient.proxyClient(HelloService.class);String s = hello.sayHello("dd");System.out.println(s);} }想了解更多精彩內(nèi)容請(qǐng)關(guān)注我的公眾號(hào)
本人簡(jiǎn)書blog地址:http://www.jianshu.com/u/1f0067e24ff8????
點(diǎn)擊這里快速進(jìn)入簡(jiǎn)書
GIT地址:http://git.oschina.net/brucekankan/
點(diǎn)擊這里快速進(jìn)入GIT
總結(jié)
- 上一篇: 《Java 进阶之路》 下--推荐书籍
- 下一篇: 从零手写IOC