Basic concepts
RPC (Remote Procedure Call) remote procedure call, a simple understanding is that one node requests services provided by another node. This protocol allows programs running on one computer to call subroutines of another computer, and programmers do not need to program this interaction additionally. RPC's most direct function is microservices.
RPC communication process
There are many RPC communication processes introduced online, so I will not introduce them separately here. The specific process is as follows:
Initiate the call in the form of a local call;
After receiving the call, stub is responsible for packaging and encoding the called method names, parameters, etc. into a specific format to form a message body transmitted on the network;
stub sends the message body to the server through the network;
After receiving the message through the network, stub unpacks and decodes it according to the corresponding format to obtain the method name and parameters;
stub is called locally based on method name and parameters;
6. After the local call of the callee (Server) is executed, the result will be returned to the Server stub;
stub packages the return value and encodes it into a message;
8. Send to Client via the network;
After receiving the message, stub unpacks and decodes it and returns it to the Client;
Get the final result of this RPC call.
RPC implementation
Server side
package main import ( "net" "net/http" "net/rpc" "strings" ) type EchoUtil struct { } func (echo *EchoUtil) CountString(str string, rsp *int) error { *rsp = (str, "s") return nil } func main() { echoUtil := new(EchoUtil) /*Register the service object*/ err := (echoUtil) if err != nil { () } () /* Fixed port for monitoring*/ listen, err := ("tcp", ":9999") if err != nil { panic(()) } (listen, nil) }
Client
package main import ( "fmt" "net/rpc" ) func main() { cli, err := ("tcp", "localhost:9999") if err != nil { panic(()) } var resp *int /*Use synchronous call method*/ err = ("", "this is test", &resp) if err != nil { panic(()) } (*resp) }
This is the end of this article about golang implementing simple rpc calls. For more related golang rpc calls, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!