RPC Is the full name of Remote Procedure Call, It is a way of communication between processes . Allow remote services to be called as if they were local services .

about RPC Summary of :

* simple :RPC The semantics of the concept is very simple and clear , This makes it easier to build distributed computing .
* High efficiency : Procedure calls look very simple and efficient .
* currency : In the single computer computing process, there are often different algorithms and API, In cross process call, the most important is the common communication mechanism .
about RPC The technical points of framework implementation are summarized as follows :

* A remote service provider needs some form of information about service invocation , Including but not limited to the definition of service interface , data structure , Or intermediate state service definition file .
* Remote proxy object : The service called by the service caller actually lists the proxy of the remote service .
* signal communication :RPC The framework is independent of the specific communication protocol
* serialize : Remote communication needs to convert the object into binary code stream for transmission , Different types of data serialization framework support , Packet size , Exception types and performance are different .
The simplest RPC Framework implementation :

* Service provider , Running on the server , Responsible for service interface definition and implementation .
* Service publisher , Running on RPC Server , Responsible for publishing local services to remote services , For other consumers to call
* Local service agent , Running on RPC client , Invoking a remote service provider through a proxy , The results are then packaged and returned to local consumers
The following is the specific implementation ,
definition EchoService Interface , The code is as follows
/** * @author zhuowen_pan. * @version 1.0.0 */ public interface EchoService {
String sayHello(String name); }
EchoServiceImpl Defines the implementation class of the interface
/** * @author zhuowen_pan. * @version 1.0.0 */ public class EchoServiceImpl
implements EchoService { @Override public String sayHello(String name) { return
name ==null ? "hello nobody" : "hello " + name; } }
RPC Implementation of server service publisher code
/** * @author zhuowen_pan. * @version 1.0.0 */ public class RpcExporter {
private static Executor executor =
Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());public
static void exporter(String hostName, int port) throws Exception { ServerSocket
serverSocket =new ServerSocket(); serverSocket.bind(new
InetSocketAddress(hostName, port));try { while (true) { executor.execute(new
ExporterTasks(serverSocket.accept())); } }finally { serverSocket.close(); } }
private static class ExporterTasks implements Runnable { Socket client = null;
public ExporterTasks(Socket client) { this.client = client; } @Override public
void run() { ObjectInputStream input = null; ObjectOutputStream out = null; try
{ input =new ObjectInputStream(client.getInputStream()); String interfaceName =
input.readUTF(); Class<?> service = Class.forName(interfaceName); String
methodName = input.readUTF(); Class<?>[] paramsTypes = (Class<?>[])
input.readObject(); Object[] args = (Object[]) input.readObject(); Method
method = service.getMethod(methodName, paramsTypes); Object result =
method.invoke(service.newInstance(), args); out =new
ObjectOutputStream(client.getOutputStream()); out.writeObject(result); }catch
(Exception e) { e.printStackTrace(); }finally { try { if (out != null) {
out.close(); }if (input != null) { input.close(); } if (client != null) {
client.close(); } }catch (Exception e) { e.printStackTrace(); } } } } }
Main responsibilities of service publisher

* As a server , Monitor client's TCP link , After receiving the client's hunger link, it is encapsulated into Tsak To the thread pool for execution
* The code stream sent by the client is de sequenced into an object , The implementer of the reflection call service , Get execution results
* Deserialize results , adopt Socket Send to client
* After remote service call ends , Releasing resources
RPC Client local service proxy source code is as follows
/** * @author zhuowen_pan. * @version 1.0.0 */ public class RpcImporter<S> {
public S importer(final Class<?> serviceClass, final InetSocketAddress address)
{return (S) Proxy.newProxyInstance(serviceClass.getClassLoader(), new
Class<?>[]{serviceClass.getInterfaces()[0]}, (proxy, method, args) -> { Socket
socket =null; ObjectOutputStream outputStream = null; ObjectInputStream
inputStream =null; try { socket = new Socket(); socket.connect(address);
outputStream =new ObjectOutputStream(socket.getOutputStream());
outputStream.writeUTF(serviceClass.getName());
outputStream.writeUTF(method.getName());
outputStream.writeObject(method.getParameterTypes());
outputStream.writeObject(args); inputStream =new
ObjectInputStream(socket.getInputStream());return inputStream.readObject(); }
catch (Exception e) { e.printStackTrace(); } finally { try { if(outputStream !=
null) { outputStream.close(); } if (inputStream != null) { inputStream.close();
}if (socket != null) { socket.close(); } } catch (Exception e) {
e.printStackTrace(); } }return null; }); } }
The functions of the local service's proxy are as follows

* Convert local interface calls to JDK Dynamic agent for , Calling interface in dynamic proxy
* establish Socket client , The provider that invokes the remote service based on the specified address
* Call the required interface class for the remote interface , Method name , The parameter list is encoded and sent to the server
* Synchronous blocking waiting for the server to return a reply , Get execution results

Test code
/** * @author zhuowen_pan. * @version 1.0.0 */ public class Client { public
static void main(String[] args) { new Thread(() -> { try { RpcExporter.exporter(
"127.0.0.1", 8088); } catch (Exception e) { e.printStackTrace(); } }).start();
RpcImporter<EchoService> importer =new RpcImporter<>(); EchoService echoService
= importer.importer(EchoServiceImpl.class,new InetSocketAddress("127.0.0.1",
8088)); System.out.println(echoService.sayHello(peter)); } }
Operation results

Here's a simple one RPC The service framework is implemented .

Technology
©2019-2020 Toolsou All rights reserved,
Ai Wei also talks about project management , On grass roots management Result Encapsulation of return result information C#/.NET System optimization (redis Chapter 6 data structure 【List】)( Essence )2020 year 7 month 30 day Wechat applet Use of modules python Short circuit logic in mysql No backup recovery Note 14 : The second biggest obstacle to motivating others in R & D management Huawei Mate 40 Pro+ 5G exposure : Leica film lens , Ceramic body Mybatis Mapping file Mapper.xml in # and $ The difference between Summary of artificial intelligence algorithm