This is the 13th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

RPC, short for Remote Procedure Call, is a popular method of communication between different nodes in distributed systems.

A complete RPC architecture contains four core components, namely Client,Server,Client Stub and Server Stub, which can be understood as stubs. Tell us about these components separately:

  • A Client is the caller of a service.
  • A Server is a real service provider.
  • Client stubs that store server address messages and package client request parameters into network messages that are sent to the server remotely over the network.
  • The server stub receives the message sent from the client, unpacks the message, and invokes local methods.

Hello, World

Go language RPC package path is NET/RPC, you can guess that the RPC package is based on the NET package. Let’s try to implement a print example based on RPC.

The service side server

Construct a HelloService type, where Hello is used to print:

server

package main

import (
	"log"
	"net"
	"net/rpc"
)

// HelloService is rpc server obj
type HelloService struct {}

func (p *HelloService) Hello(request string, reply *string) error {
	*reply = "hello:" + request
	return nil
}

// Register an object of type HelloService as an RPC service
func main(a){
	rpc.RegisterName("HelloService".new(HelloService))

	listener, err := net.Listen("tcp".": 1234")
	iferr ! =nil {
		log.Fatal("ListenTCP error:", err)
	}

	conn, err := listener.Accept()
	iferr ! =nil {
		log.Fatal("Accept error", err)
	}

	rpc.ServeConn(conn)
  
}
Copy the code

The Hello method must meet the RPC rules of the Go language:

  • A method can have only two serializable arguments, the second of which is a pointer

type

  • It returns an error and must be a public method.

The rpc.Register function call registers all object methods of the object type that meet the RPC rules as RPC functions, all registered

Is placed under the “HelloService” service space.

Establish a unique TCP connection and provide RPC services to the other party on that TCP connection through the rpc.serveconn function.

The client clinet

Client request HelloService service code:

package main

import (
	"fmt"
	"log"
	"net/rpc"
)

func main(a) {
	client, err := rpc.Dial("tcp"."localhost:1234")
	iferr ! =nil {
		log.Fatal("dialing err:", err)
	}

	var reply string
	err = client.Call("HelloService.Hello"."test_rpc", &reply)
	iferr ! =nil {
		log.Fatal(err)
	}

	fmt.Println(reply)
}
Copy the code

Dial the RPC service, and then invoke the specific RPC methods through client.Call. In the call

In client.Call, the first parameter is the name of the RPC service and method linked by dots, and the second and third parameters are defined as two parameters of the RPC method respectively.

Start the server. Start the client. The client execution result is as follows:

$ go run client.go
hello:test_rpc
Copy the code