您好,欢迎访问一九零五行业门户网

Java 手写一个RPC框架

rpc框架称为远程调用框架,其实现的核心原理就是消费者端使用动态代理来代理一个接口的方法(基于jdk的动态代理,当然如果使用cglib可以直接使用无接口类的方法),通过加入网络传输编程,传输调用接口方法名称,方法参数来给提供者获取,再通过反射,来执行该接口的方法,再将反射执行的结果通过网络编程传回消费者端。
现在我们来依次实现这些概念。这里我们做最简单的实现,网络编程使用的是bio,大家可以使用reactor模式的netty来改写性能更好的方式。而网络传输中使用的序列化和反序列化也是java自带的,当然这样的传输字节比较大,可以使用google的protobuffer或者kryo来处理。这里只为了方便说明原理。
pom
<?xml version="1.0" encoding="utf-8"?><project xmlns="http://maven.apache.org/pom/4.0.0" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="http://maven.apache.org/pom/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelversion>4.0.0</modelversion> <groupid>com.guanjian</groupid> <artifactid>rpc-framework</artifactid> <version>1.0-snapshot</version> <build> <plugins> <plugin> <groupid>org.apache.maven.plugins</groupid> <artifactid>maven-compiler-plugin</artifactid> <version>3.7.0</version> <configuration> <source>1.8</source> <target>1.8</target> <encoding>utf-8</encoding> </configuration> </plugin> </plugins> </build></project>
首先当然是我们要进行远程调用的接口以及接口的方法。
public interface helloservice { string sayhello(string content);}
接口实现类
public class helloserviceimpl implements helloservice { public string sayhello(string content) { return "hello," + content; }}
消费者端的动态代理,如果你是把提供者和消费者写在两个工程中,则提供者端需要上面的接口和实现类,而消费者端只需要上面的接口。
public class consumerproxy { /** * 消费者端的动态代理 * @param interfaceclass 代理的接口类 * @param host 远程主机ip * @param port 远程主机端口 * @param <t> * @return */ @suppresswarnings("unchecked") public static <t> t consume(final class<t> interfaceclass,final string host,final int port) { return (t) proxy.newproxyinstance(interfaceclass.getclassloader(), new class[]{interfaceclass}, (proxy,method,args) -> { //创建一个客户端套接字 socket socket = new socket(host, port); try { //创建一个对外传输的对象流,绑定套接字 objectoutputstream output = new objectoutputstream(socket.getoutputstream()); try { //将动态代理的方法名写入对外传输的对象流中 output.writeutf(method.getname()); //将动态代理的方法的参数写入对外传输的对象流中 output.writeobject(args); //创建一个对内传输的对象流,绑定套接字 //这里是为了获取提供者端传回的结果 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(); } } ); }}
有关jdk动态代理的内容可以参考aop原理与自实现 ,bio的部分可以参考传统io与nio比较
提供者端的网络传输和远程方式调用服务
public class providerreflect { private static final executorservice executorservice = executors.newcachedthreadpool(); /** * rpc监听和远程方法调用 * @param service rpc远程方法调用的接口实例 * @param port 监听的端口 * @throws exception */ public static void provider(final object service,int port) throws exception { //创建服务端的套接字,绑定端口port serversocket serversocket = new serversocket(port); while (true) { //开始接收客户端的消息,并以此创建套接字 final socket socket = serversocket.accept(); //多线程执行,这里的问题是连接数过大,线程池的线程数会耗尽 executorservice.execute(() -> { try { //创建呢一个对内传输的对象流,并绑定套接字 objectinputstream input = new objectinputstream(socket.getinputstream()); try { try { //从对象流中读取接口方法的方法名 string methodname = input.readutf(); //从对象流中读取接口方法的所有参数 object[] args = (object[]) input.readobject(); class[] argstypes = new class[args.length]; for (int i = 0;i < args.length;i++) { argstypes[i] = args[i].getclass(); } //创建一个对外传输的对象流,并绑定套接字 //这里是为了将反射执行结果传递回消费者端 objectoutputstream output = new objectoutputstream(socket.getoutputstream()); try { class<?>[] interfaces = service.getclass().getinterfaces(); method method = null; for (int i = 0;i < interfaces.length;i++) { method = interfaces[i].getdeclaredmethod(methodname,argstypes); if (method != null) { break; } } object result = method.invoke(service, args); //将反射执行结果写入对外传输的对象流中 output.writeobject(result); } catch (throwable t) { output.writeobject(t); } finally { output.close(); } } catch (exception e) { e.printstacktrace(); } finally { input.close(); } } finally { socket.close(); } } catch (exception e) { e.printstacktrace(); } }); } }}
启动提供者端的网络侦听和远程调用
public class rpcprovidermain { public static void main(string[] args) throws exception { helloservice service = new helloserviceimpl(); providerreflect.provider(service,8083); }}
启动消费者的动态代理调用
public class rpcconsumermain { public static void main(string[] args) throws interruptedexception { helloservice service = consumerproxy.consume(helloservice.class,"127.0.0.1",8083); for (int i = 0;i < 1000;i++) { string hello = service.sayhello("你好_" + i); system.out.println(hello); thread.sleep(1000); } }}
运行结果
hello,你好_0
hello,你好_1
hello,你好_2
hello,你好_3
hello,你好_4
hello,你好_5
.....
如果你要扩展成一个netty+protobuffer的高性能rpc框架可以参考netty整合protobuffer 的相关写法。
推荐教程:《php》
以上就是java 手写一个rpc框架的详细内容。
其它类似信息

推荐信息