Article directory
The imitation
gRPC
function implements calling other server methods just like calling local methods.
gRPC
function implements calling other server methods just like calling local methods.
Introduction
Before introducing gRPC
the 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, HTTP
although 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 TCP
to speed up the transmission efficiency. .
RPC
RPC
The full name is Remote Procedure Call
remote 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
gRPC
Is a high-performance, open source and general-purpose RPC
framework for mobile and HTTP/2
design. Currently C
, language versions of , Java
and are available Go
, respectively: grpc
, grpc-java
, grpc-go.
where C
version supports C
, C++
, Node.js
, Python
, Ruby
, Objective-C
, PHP
and C#
supports.
Chinese documentation: http://doc.oschina.net/grpc
In gRPC
, we call the caller client
, and the callee server
. Like other RPC
frameworks, gRPC
it 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, gRPC
the underlying details will be shielded. client
You only need to directly call the defined methods to get the expected return results. For server
the end, we also need to implement the methods we defined. Similarly, gRPC
it 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 server
implement this interface and client
call the proxy object of this interface. As for the other details, leave them to me gRPC
.
gRPC
interaction logic
Server side logic
- Creating
gRPC Server
an object can be understood asServer
an abstract object. - Register
server
(which contains the server interface that needs to be called) togRPC Server
the 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
Listen
and listenTCP
on the port. gRPC Server
Startlis.Accept
untilStop
.
client logic
- Creates a connection interaction with the given target server.
server
The client object created .- Send
RPC
a 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.
Native implementation of imitation gRPC
framework
Because gRPC
the framework currently does not support it IRIS/Caché
, here we understand gRPC
the principle and imitate gRPC
the 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 IRIS
as server.
Write client methods
- 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 serverIP
.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
}
}
- Create empty classes
M.Login
,M.Pay
,M.Stock
and inherit them respectivelyUtil.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.
-
Write methods according to the regular method calling pattern.
-
There is actually no method here ,
Login
because the class created in the previous step is an empty class.Pay
Stock
-
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
- Create a server-side listening
Util.RPC.Server
class, which simulatesgRPC
creatingServer
objects, creatingListen
, and listeningTCP
ports. code show as below:- The parameters
PORT
are the interfaces that the server monitors and opens.
- The parameters
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
}
}
-
Write server-side
M.Login
methodsLogin
,M.Pay
methodsPay
,M.Stock
methodsStock
.-
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.
-
Comprehensive demonstration
-
IRIS
Enable the listening method on the server side. -
The client
Caché
calls the salesperson method without awareness of business logicBiz()
.-
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
client
only needs to directly call the defined methods.
-
In this way, we have achieved a similar gRPC
function 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.