gRPC

Get started with gRPC

Photo by Mauro Gigli on Unsplash

gRPC is a modern open source high performance RPC framework that can run in any environment. It can efficiently connect services in and across data centers with pluggable support for load balancing, tracing, health checking and authentication. It is also applicable in last mile of distributed computing to connect devices, mobile applications and browsers to backend services.

To use gRPC we need protocol buffer compiler.

Download and install protocol buffer compiler for ubuntu by running apt install command

sudo apt install -y protobuf-compiler

Check protobuf version

protoc --version
libprotoc 3.0.0

Setup the server and client example in Go

go.mod

go 1.15

require (
github.com/golang/protobuf v1.4.3 // indirect
google.golang.org/grpc v1.33.0
google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.0.0 // indirect
google.golang.org/grpc/examples v0.0.0-20201016185254-4be647f7f6db
)

client/main.go

import (
"context"
"log"
"os"
"time"

"google.golang.org/grpc"
pb "google.golang.org/grpc/examples/helloworld/helloworld"
)

const (
address = "localhost:50051"
defaultName = "world"
)

func main() {
// Set up a connection to the server.
conn, err := grpc.Dial(address, grpc.WithInsecure(), grpc.WithBlock())
if err != nil {
log.Fatalf("did not connect: %v", err)
}
defer conn.Close()
c := pb.NewGreeterClient(conn)

// Contact the server and print out its response.
name := defaultName
if len(os.Args) > 1 {
name = os.Args[1]
}
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())
}

server/main.go

import (
"context"
"log"
"net"

"google.golang.org/grpc"
pb "google.golang.org/grpc/examples/helloworld/helloworld"
)

const (
port = ":50051"
)

// server is used to implement helloworld.GreeterServer.
type server struct {
pb.UnimplementedGreeterServer
}

// SayHello implements helloworld.GreeterServer
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() {
lis, err := net.Listen("tcp", port)
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
s := grpc.NewServer()
pb.RegisterGreeterServer(s, &server{})
if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}

Running server and client will show:

2020/10/17 17:16:20 Greeting: Hello world

References

A passionate automation engineer who strongly believes in “A man can do anything he wants if he puts in the work”.

Get the Medium app