preface

Read an article about yesterday with a few lines of code to achieve the RPC framework blog javatar.iteye.com/blog/112391… Therefore, I would like to clarify my thoughts on the basis of this blog, add more notes as much as possible, and further reduce the threshold of learning the principle of RPC framework.

Schematic diagram

Start with a schematic to help you understand the rest of the code.

code

RpcFramework core classes

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; Public class RpcFramework {/** * exposes services ** @param Service service implementation * @param port service port * @throws Exception */ public static voidexport(final Object service, int port) throws Exception {

        System.out.println("Export service " + service.getClass().getName() + " on port "+ port); ServerSocket server = new ServerSocket(port); // Always polling, compared towhile(true), which gives better performancefor(;;) {try {// block until a consumer requests final Socket Socket = server.accept(); New Thread(() -> {try {try {ObjectInputStream input = new ObjectInputStream(socket.getInputStream()); Try {// The consumer sends the required method information in three batches, as shown herereadUTF(),readString methodName = input.readutf (); Class<? >[] parameterTypes = (Class<? >[])input.readObject(); Object[] arguments = (Object[])input.readObject(); ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream()); Method = service.getClass().getMethod(methodName, parameterTypes); Object result = method.invoke(service, arguments); // Return the result to consumer 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(); }} /** * Reference service ** @param <T> Interface generic * @param interfaceClass Interface type * @param host server host name * @param port Server port * @returnRemote service * @throws Exception */ @SuppressWarnings("unchecked")
    public static <T> T refer(final Class<T> interfaceClass, final String host, final int port) throws Exception {

        System.out.println("Get remote service " + interfaceClass.getName() + " from server " + host + ":"+ port); Using JDK dynamic proxies, the call to the refer method is returned directly to an object that has been processed by the dynamic proxyreturn(T) Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class<? >[] {interfaceClass}, newInvocationHandlerPublic Object invoke(Object proxy, Method Method, Override) {public Object invoke(Object proxy, Method Method, Override); Object[] arguments) throws Throwable {// Remote RPC requests are initiated when the method is actually called provider executes the service Socket Socket = new Socket(host, port); try { ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream()); Output.writeutf (method.getName())); output.writeObject(method.getParameterTypes()); output.writeObject(arguments); ObjectInputStream input = new ObjectInputStream(socket.getInputStream()); Object result = input.readObject();if (result instanceof Throwable) {
                                throw (Throwable) result;
                            }
                            returnresult; } finally { input.close(); } } finally { output.close(); } } finally { socket.close(); }}}); }}Copy the code

The service interface

public interface HelloService {

    String hello(String name);

}

Copy the code

Service interface implementation

public class HelloServiceImpl implements HelloService {

    @Override
    public String hello(String name) {
        System.out.println("Called");
        return "Hello"+ name; }}Copy the code

The provider bootstrap class

public class RpcProvider { public static void main(String[] args) throws Exception { HelloService service = new HelloServiceImpl(); RpcFramework.export(service, 1234); }}Copy the code

Consumer guide class

public class RpcConsumer { public static void main(String[] args) throws Exception { HelloService = 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); }}}Copy the code

The following figure shows the class structure of the Provider project

conclusion

A brief summary of the simple RPC framework, the blogger is learning the principle of Dubbo recently, so did not extend too much about distributed content, I hope to write an article about distributed content with the further learning, mutual encouragement!