Mastering RPC: From Concepts to gRPC Implementation in Go
This article explains the fundamentals of Remote Procedure Call (RPC), its historical origins, the step‑by‑step execution process, and provides a practical guide to installing and using gRPC with Protocol Buffers in Go, including full code examples and advantages.
Abstract: RPC (Remote Procedure Call) allows a program on one computer to request services from a program on another computer without needing to understand the underlying network protocols. Typical RPC frameworks include Alibaba's Dubbo, Google's gRPC, Facebook's Thrift, and Twitter's Finagle.
RPC Basics
RPC is a protocol that enables a node to request services from another node, making remote calls appear similar to local method invocations. Any framework adhering to the RPC specification can be considered an RPC framework.
RPC Mechanism and Implementation Process
RPC involves interaction between a caller and a callee process, providing a local‑like method call experience for the caller.
Origins and Fundamental Concepts of RPC
In 1984, Birrell and Nelson published “Implementing Remote Procedure Calls,” which formally described the RPC mechanism.
When a process on computer A invokes a method on computer B, the caller on A is suspended while B executes the method and returns the result, after which A resumes execution.
The caller sends parameters to the callee, which processes them and returns results, all transparent to developers who need not know the underlying message passing details.
RPC makes remote calls resemble local calls; for example, a program reading a file uses a read system call locally, but when the call is remote, a client stub packages parameters into a network message, sends it to the server, blocks, and waits for the response.
When the read operation is remote, the client stub behaves like a local function call but transmits the parameters over the network and waits for the server’s response.
Below is a diagram illustrating the client‑server interaction stages.
Summary of RPC Execution Steps
Invoke the client handle and pass parameters.
Use the local kernel to send a network message.
The message travels to the remote host (the server).
The server handle receives and parses the message.
The server executes the called method and returns the result.
The server handle sends the result back via the kernel.
The message traverses the network back to the client.
The client receives the data.
Installing gRPC and Protobuf
gRPC, developed by Google, is a language‑neutral, platform‑neutral, open‑source RPC system. Clients and servers can be written in different languages (e.g., a Java server with a Go client). A single .proto file defines services, and code can be generated for any supported language, making remote calls feel like local function calls.
Generating server code from a .proto file produces a skeleton that abstracts low‑level communication; generating client code produces a stub that hides language differences.
Installation
go get github.com/golang/protobuf/proto
go get google.golang.org/grpc (if unavailable, use the following commands)
After installation, protoc-gen-go.exe appears in $GOPATH/bin.
Download protoc.exe (e.g., version 3.9.0) from the official releases and place it in $GOPATH/bin.
Defining Services with proto
gRPC uses Protocol Buffers to define service interfaces. Protocol Buffers are a language‑neutral, efficient binary serialization format, smaller and faster than XML or JSON, and support automatic code generation.
import "myproject/other_protos.proto"; // import other proto files
syntax = "proto3"; // specify proto version
package hello; // default package name
// Go package option
option go_package = "hello";
message SearchRequest {
required string query = 1; // mandatory field
optional int32 page_number = 2 [default = 10]; // optional field
repeated int32 result_per_page = 3; // repeated field
}
message SearchResponse {
message Result {
required string url = 1;
optional string title = 2;
repeated string snippets = 3;
}
repeated Result result = 1;
}
message SomeOtherMessage {
optional SearchResponse.Result result = 1; // reuse other message
}
service List {
rpc getList (SearchRequest) returns (SearchResponse);
} protoc --go_out=plugins=grpc:. *.protoImplement the server logic, register it with a gRPC server, and start listening. Clients use a blocking stub, communicating synchronously over HTTP/2 with binary Protocol Buffer messages.
Advantages of gRPC
Efficient inter‑process communication using binary Protocol Buffers over HTTP/2.
Simple service interface definition and easy extensibility.
Strong typing and cross‑language support.
Supports unary RPC, server streaming, client streaming, and bidirectional streaming.
Getting Started with gRPC
Simple Usage
protocol buffer syntax = "proto3";
package hello;
// Define service
service Greeter {
rpc SayHello (HelloRequest) returns (HelloReply) {}
}
message HelloRequest {
string name = 1;
}
message HelloReply {
string message = 1;
}Server implementation (Go):
package main
import (
"context"
"flag"
"fmt"
"log"
"net"
"google.golang.org/grpc"
pb "mygrpc/proto/hello"
)
var (
port = flag.Int("port", 50051, "The server port")
)
type server struct {
pb.UnimplementedGreeterServer
}
func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
log.Printf("Received: %v", in.GetName())
return &pb.HelloReply{Message: "Hello " + in.GetName()}, nil
}
func main() {
flag.Parse()
lis, err := net.Listen("tcp", fmt.Sprintf(":%d", *port))
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
s := grpc.NewServer()
pb.RegisterGreeterServer(s, &server{})
log.Printf("server listening at %v", lis.Addr())
if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}Client implementation (Go):
package main
import (
"context"
"flag"
"log"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
pb "mygrpc/proto/hello"
)
const (
defaultName = "world"
)
var (
addr = flag.String("addr", "localhost:50051", "the address to connect to")
name = flag.String("name", defaultName, "Name to greet")
)
func main() {
flag.Parse()
conn, err := grpc.Dial(*addr, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
log.Fatalf("did not connect: %v", err)
}
defer conn.Close()
c := pb.NewGreeterClient(conn)
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
r, err := c.SayHello(ctx, &pb.HelloRequest{Name: *name})
if err != nil {
log.Fatalf("could not greet: %v", err)
}
log.Printf("Greeting: %s", r.GetMessage())
}The client connects to the gRPC server and can invoke remote methods just like local functions.
Code Repository
https://github.com/onenewcode/mygrpc.git
You can also download the bundled resources directly.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
