Imitation of `gRPC` function to call other server methods like calling local methods

The imitation gRPC function implements calling other server methods just like calling local methods.

Introduction

Before introducing gRPCthe introduction, let us first understand the concept:

Monolithic architecture

A simple understanding of the monolithic architecture is that all business codes are on one server. Once a certain service goes down, the entire application will be unavailable and the isolation will be poor. Only the overall application can be scaled, for example, the entire application is packaged and deployed on one or more servers, which wastes resources and has poor scalability. The code is coupled together and has poor maintainability.

Microservice architecture

Solve the disadvantages of monolithic architecture. It can be split into multiple services as needed. For example, if there are many requests for users and few requests for payment, the user business function can be split into multiple servers, and the payment business function can be split into a single server.

There are also some disadvantages, such as code redundancy, and the same code must be written on multiple servers, such as interfaces. There is a calling relationship between services. After the service is split, there are calls between services and processes, and calls between servers.

At this time, you need to initiate a network call. Network calls are generally used HTTP, but in the microservice architecture, HTTPalthough it is convenient, its performance is low. At this time, you need to introduce RPC(remote procedure call) and initiate the call through a custom protocol TCPto speed up the transmission efficiency. .

RPC

RPCThe full name is Remote Procedure Callremote procedure call. This is a protocol that is used to shield various calling details in distributed computing , allowing you to directly call a remote function like a local call.

gPRC

gRPCIs a high-performance, open source and general-purpose RPCframework for mobile and HTTP/2design. Currently C, language versions of , Javaand are available Go, respectively: grpc, grpc-java, grpc-go.where Cversion supports C, C++, Node.js, Python, Ruby, Objective-C, PHPand C#supports.

Chinese documentation: http://doc.oschina.net/grpc

In gRPC, we call the caller client, and the callee server. Like other RPCframeworks, gRPCit is also based on the idea of ​​service definition. To put it simply, we describe a service in a certain way, which is language-independent. In the process of defining this service, we describe what the service name is, what methods can be called, what input parameters these methods have, and what kind of return parameters they have.

In other words, after these services and methods are defined, gRPCthe underlying details will be shielded. clientYou only need to directly call the defined methods to get the expected return results. For serverthe end, we also need to implement the methods we defined. Similarly, gRPCit will also help us shield the underlying details. We only need to implement the specific logic of the defined method.

It can be found that in the above description process, the so-called service definition is very close to the semantics of defining an interface. I prefer to understand this as an "agreement". Both parties agree on an interface, then serverimplement this interface and clientcall the proxy object of this interface. As for the other details, leave them to me gRPC.

gRPCinteraction logic

Server side logic

  • Creating gRPC Serveran object can be understood as Serveran abstract object.
  • Register server(which contains the server interface that needs to be called) to gRPC Serverthe internal registration center.
    • This can be discovered through internal services when a request is received. Discover the server interface and transfer it for logical processing.
  • Create Listenand listen TCPon the port.
  • gRPC ServerStart lis.Acceptuntil Stop.

client logic

  • Creates a connection interaction with the given target server.
  • serverThe client object created .
  • Send RPCa request, wait for the synchronous response, and return the response result after getting the callback.
  • Output the response knot.

sample graph

As shown in the figure below: the business server calls the login business server, payment server, and inventory server.

insert image description here

Native implementation of imitation gRPCframework

Because gRPCthe framework currently does not support it IRIS/Caché, here we understand gRPCthe principle and imitate gRPCthe framework to achieve similar functions. Call code methods on other servers without awareness by writing code normally.

Note: To show this, use Cachéas client and IRISas server.

Write client methods

  1. First, create a client class on the client side, that is, the calling side Util.RPC.Client. The code is as follows:
    • %DispatchClassMethod- Dynamic dispatching method is the key to achieving imperceptibility.
    • SERVERIP- The address of the target server IP.
    • PORT- The port number of the target server.
Class Util.RPC.Client Extends %RegisteredObject
{
    
    

Parameter SERVERIP = "127.0.0.1";

Parameter PORT = 7788;

ClassMethod %DispatchClassMethod(class As %String, method As %String, args...) [ ServerOnly = 1 ]
{
    
    
	
	#; 客户端通信、客户端需要设置服务器IP与端口号
	#dim clientSocket As %IO.Socket = ##class(%IO.Socket).%New()
	s host = ..#SERVERIP
	s port = ..#PORT
	s clientSocket.TranslationTable = "UTF8"
	
	d clientSocket.Open(host, port, .sc)
	
	s obj = {
    
    }	//注释1
	s obj.class = class
	s obj.method = method
	
	s params = []
	
	s i = ""
	for {
    
    
		s i = $o(args(i))
		q:(i = "")
		d params.%Push(args(i))
	}
	
	s obj.params = params
	d clientSocket.WriteLine(obj.%ToJSON())	//注释2
	
	while (1) {
    
    

		s data = clientSocket.ReadLine() 
		if (data '= "" ){
    
    	//注释3
			ret data
		}
		
	}
	
	q $$$OK
}

}
  1. Create empty classes M.Login, M.Pay, M.Stockand inherit them respectively Util.RPC.Client.
    • The purpose is to simulate the interactive interface, because to call other server methods, you must first determine the name of the server interface to be called.

insert image description here

  1. Write methods according to the regular method calling pattern.

    • There is actually no method here , Loginbecause the class created in the previous step is an empty class.PayStock

    • If you call the method directly as usual, you will definitely get an error that the method does not exist. Here we are actually calling the server-side method.

    • It can be observed that the code here is written in a normal way of calling class methods, and there are no other additional operations.

Class M.RPC Extends %RegisteredObject
{
    
    

/// d ##class(M.RPC).Biz()
ClassMethod Biz()
{
    
    
	w ##class(M.Login).Login("yx","123456"),!
	w ##class(M.Pay).Pay(100),!
	w ##class(M.Stock).Stock(3),!
}

}

Write server-side methods

  1. Create a server-side listening Util.RPC.Serverclass, which simulates gRPCcreating Serverobjects, creating Listen, and listening TCPports. code show as below:
    • The parameters PORTare the interfaces that the server monitors and opens.
Class Util.RPC.Server Extends %RegisteredObject
{
    
    

Parameter PORT = 7788;

/// d ##class(Util.RPC.Server).ServerRPC()
ClassMethod ServerRPC()
{
    
    
	#; 服务端通信、服务端需要打开端口,等待客户端通信
	#dim severSocket As %IO.ServerSocket = ##class(%IO.ServerSocket).%New()
	s port = ..#PORT
	s severSocket.TranslationTable="UTF8"
	s severSocket.ConnectionQueueSize = 2
	
	d severSocket.Open(port, 10, .sc)
	q:($$$ISERR(sc)) "Open:" _ $System.Status.GetOneErrorText(sc)
	
	d severSocket.Listen(10, .sc)
	q:($$$ISERR(sc)) "Listen:" _ $System.Status.GetOneErrorText(sc)
	
	while (1) {
    
    
		s data =  severSocket.ReadLine()
		if (data '= "") {
    
    
			s obj = {
    
    }.%FromJSON(data)	//注释1
			s arg = obj.params.%Size()
			for i = 1 : 1 : arg{
    
    
				s arg(i) = obj.params.%Get(i - 1)
			}
			s ret = $classmethod(obj.class, obj.method, arg...)	//注释2
			d severSocket.WriteLine(ret)	//注释3
		}
	}

	q $$$OK
}

}
  1. Write server-side M.Loginmethods Login, M.Paymethods Pay, M.Stockmethods Stock.

    • The server is used here IRIS, and the implemented methods are all on the server, but the client does not have this method.

    • The methods called by the client are actually methods on the server.

insert image description here

Comprehensive demonstration

  1. IRISEnable the listening method on the server side.

  2. The client Cachécalls the salesperson method without awareness of business logic Biz().

    • It can be observed that the client directly calls the server's method, and the coding method is no different from normal writing code.

    • The client does not need to know the underlying details and clientonly needs to directly call the defined methods.

insert image description here

In this way, we have achieved a similar gRPCfunction and called the server-side program just like writing code normally.

Create value, share learning, grow together, and move forward together. Everyone is welcome to provide opinions and communicate together.

Guess you like

Origin blog.csdn.net/yaoxin521123/article/details/132636985