RPC remote process call is simple implementation

tags: Java  notes  rpc  

1. What is RPC

RPC (Remote Procedure Call Protocol) -Tarly, it is a protocol that requests services from remote computer programs through the network without understanding the underlying network technology through the network. The RPC protocol assumes the existence of certain transmission protocols, such as TCP or UDP to carry information data between communication programs. In the OSI network communication model, RPC spans the transmission layer and application layer. RPC makes it easier to develop applications including network distributed multi -program.
RPC adopts a client/server mode. The request program is a client, and the service provider is a server. First of all, the client calls the process to send a call information with process parameters to the service process, and then wait for the answer information. On the server side, the process is kept sleeping until the call information arrives. When a calling information arrives, the server gets process parameters, calculates the result, sends the answer information, and then waits for the next call information. Finally, the client calls the process to receive the response information, get the process result, and then call the execution to continue.
There are multiple RPC modes and execution. It was initially proposed by Sun Company. The IETF Onc charter has revised the SUN version, making the ONC RPC protocol a IETF standard protocol. Now use the most common mode and execution is a distributed computing environment (DCE) with open software foundation.

Second, legend description


3. Java instance demonstration
1. Implement technical solution
The following uses a relatively original scheme to implement the RPC framework, using SOCKET communication, dynamic proxy and reflection and Java native serialization.

2. RPC framework architecture
The RPC architecture is divided into three parts:

  • Service provider, runs on the server side, provides service interface definition and service implementation classes.
  • The service center, running on the server side, is responsible for publishing local services into remote services, managing remote services, and providing service consumers for use.
  • Serve consumers, run on the client, and call remote services through remote proxy objects.

3. Specific implementation
1) The definition and implementation of the service provider, the code is as follows:

package services;

public interface HelloService {
    String sayHi(String name);
}

2) HelloServices interface implementation class:

package services.impl;
import services.HelloService;
 
public class HelloServiceImpl implements HelloService {
    public String sayHi(String name) {
        return "Hi, " + name;
    }
}

3) The code implementation of the service center, the code is as follows:


package services;
import java.io.IOException;

public interface Server {
    public void stop();
    
    public void start() throws IOException;
 
    public void register(Class serviceInterface, Class impl);
 
    public boolean isRunning();

    public int getPort();
}

4) Service Center Implementation Class:

package services.impl;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import services.Server;
 
public class ServiceCenter implements Server {
    private static ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    
    private static final HashMap<String, Class> serviceRegistry = new HashMap<String, Class>();

    private static boolean isRunning = false;

    private static int port;
 
    public ServiceCenter(int port) {
        this.port = port;
    }

    public void stop() {
        isRunning = false;
        executor.shutdown();
    }
 
    public void start() throws IOException {
        ServerSocket server = new ServerSocket();
        server.bind(new InetSocketAddress(port));
        System.out.println("start server");
        try {
            while (true) {
                // 1. Surveillance of the TCP connection of the client, encapsulate it as TASK after receiving the TCP connection, and execute it by the thread pool
                executor.execute(new ServiceTask(server.accept()));
            }
        } finally {
            server.close();
        }
    }
 
    public void register(Class serviceInterface, Class impl) {
        serviceRegistry.put(serviceInterface.getName(), impl);
    }
 
    public boolean isRunning() {
        return isRunning;
    }
 
    public int getPort() {
        return port;
    }
 
    private static class ServiceTask implements Runnable {
        Socket clent = null;

        public ServiceTask(Socket client) {
            this.clent = client;
        }

        public void run() {
            ObjectInputStream input = null;
            ObjectOutputStream output = null;
            try {
                // 2. Sequence the code flow from the client into an object, the reflection call service implemented, and obtain the execution results
                input = new ObjectInputStream(clent.getInputStream());
                String serviceName = input.readUTF();
                String methodName = input.readUTF();
                Class<?>[] parameterTypes = (Class<?>[]) input.readObject();
                Object[] arguments = (Object[]) input.readObject();
                Class serviceClass = serviceRegistry.get(serviceName);
                if (serviceClass == null) {
                    throw new ClassNotFoundException(serviceName + " not found");
                }
                Method method = serviceClass.getMethod(methodName, parameterTypes);
                Object result = method.invoke(serviceClass.newInstance(), arguments);

                // 3. Serialize the execution results and send it to the client via socket
                output = new ObjectOutputStream(clent.getOutputStream());
                output.writeObject(result);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (output != null) {
                    try {
                        output.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (input != null) {
                    try {
                        input.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (clent != null) {
                    try {
                        clent.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}

5) Remote proxy object of the client:

package client;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.lang.reflect.Method;
 
public class RPCClient<T> {
    @SuppressWarnings("unchecked")
    public static <T> T getRemoteProxyObj(final Class<?> serviceInterface, final InetSocketAddress addr) {
        // 1. Convert the local interface call to the dynamic agent of JDK, and realize the remote call of the interface in the dynamic proxy in the dynamic proxy
        return (T) Proxy.newProxyInstance(serviceInterface.getClassLoader(), new Class<?>[] { serviceInterface },
                new InvocationHandler() {
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        Socket socket = null;
                        ObjectOutputStream output = null;
                        ObjectInputStream input = null;
                        try {
                            // 2. Create a socket client and connect to the remote service provider according to the specified address
                            socket = new Socket();
                            socket.connect(addr);

                            // 3. Send the required interface class, method name, parameter list and other codes required for remote service calls
                            output = new ObjectOutputStream(socket.getOutputStream());
                            output.writeUTF(serviceInterface.getName());
                            output.writeUTF(method.getName());
                            output.writeObject(method.getParameterTypes());
                            output.writeObject(args);
 
                            // 4. Synchronize blocking the server to return to the response, get the answer after getting the answer
                            input = new ObjectInputStream(socket.getInputStream());
                            return input.readObject();
                        } finally {
                            if (socket != null)
                                socket.close();
                            if (output != null)
                                output.close();
                            if (input != null)
                                input.close();
                        }
                    }
                });
    }
}

6) Finally for the test class:

package client;
import java.io.IOException;
import java.net.InetSocketAddress;
import services.HelloService;
import services.Server;
import services.impl.HelloServiceImpl;
import services.impl.ServiceCenter;

public class RPCTest {
    public static void main(String[] args) throws IOException {
        new Thread(new Runnable() {
            public void run() {
                try {
                    Server serviceServer = new ServiceCenter(8088);
                    serviceServer.register(HelloService.class, HelloServiceImpl.class);
                    serviceServer.start();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        HelloService service = RPCClient
                .getRemoteProxyObj(HelloService.class, new InetSocketAddress("localhost", 8088));
        System.out.println(service.sayHi("test"));
    }
}

operation result:

regeist service HelloService
start server
Hi, test

Intelligent Recommendation

Simple implementation of Hadoop RPC remote procedure call protocol

Simple implementation of Hadoop RPC remote procedure call protocol Simply put, RPC isClient process Remote callServer-side process The method in (I understand, not necessarily correct). 1.Java code Fi...

What is RPC (Remote Process Call)

I want to execute some functions on the A computer, but these functions actually run on the B computer; I want to call some of the B process functions on the A process. The RPC framework is needed at ...

GO RPC remote process call

/rpcintf/intf.go server/server.go client/client.go        ...

RPC implementation consumer remote call

Crack basic implementation ideas, mainly complete a function: The interface function in the API module is implemented in the server (not in the client). Therefore, when the client calls an interface m...

RPC process simple implementation

1, main code 2, analog interface Interface class Implementation 3, interface provider result: 4, consumers result:...

More Recommendation

RPC call process (Remote Procedure Call Protocol)

URL: http://blog.jobbole.com/92290/ To make network communication details transparent to users, we naturally need to encapsulate the communication details. Let ’s first look at the next RPC call...

Netty implementation simple RPC call

RPC, that is, Remote Procedure Call (remote procedure call), is a point where it is: calling services on the remote computer, just like calling local services. The RPC can be based on the HTTP or TCP ...

Dubbo simple RPC call implementation

1. Install the start ZooKeeper Registry to conduct service governance 2, generator and consumer pom.xml introduced Dubbo dependence 3, producers 3.1 Producer Writes Service Interface and Logic Impleme...

Remote Procedure Call RPC Notes (01) - RPC concept, call process

1. Basic concepts PRC Remote procedure call, which is a node requesting a service provided by another node. Local procedure call: If you want to perform related operations on local objects, you can de...

RabbitMQ Getting Started: Remote Process Call (RPC)

RabbitMQ Getting Started: Remote Process Call (RPC) If we want to call a remote approach or function and wait for the execution result, it is the remote process call (REMOTE Procedure Call). what to d...

Copyright  DMCA © 2018-2026 - All Rights Reserved - www.programmersought.com  User Notice

Top