gRPC in a Nutsell

image.png

gRPC : Introduced in 2015

With pluggable support , latest RPC for load balancing, tracing, health checking, and authentication, gRPC is well-suited for connecting microservices.

what-is-grpc?

a framework for implementing RPC APIs via HTTP/2 which uses Protocol Buffers and HTTP/2.

Existing concept but utilises latest technologies and takes different route.

how does it achieve such performance? Uses HTTP/2 instead of HTTP/1.1 Uses Protocol Buffers instead of XML / JSON

http/2 -- BInary Framing Layer

image.png

1) How to get started with gRPC ?

The First step , we need to know Protocol Buffer and its format

gRPC uses Protocol Buffers for communications , It's payload size is smaller than XML & JSON ,So we save in Bandwidth with gRPC

Protocol Buffers is a free and open source cross-platform library used to serialize structured data and can be useful in developing programs to communicate with each other over a network or for storing data.

It was developed by Google for serializing structured data and uses **binary encoding format **that allows you to specify a schema for your data.

Steps :

  1. Create Message using Protocol Buffer in .proto file

  2. Generate code from this .proto file

  3. Write server program

  4. Write client program

  5. Run server

  6. Run client

2) How to define our data in Protocol Buffer now ?

**Step 1: ** create a file with .proto extension as in:

Create Message using Protocol Buffer in .proto file eg : Student.proto

syntax = "proto3";
   option go_package = "./main";

   message Student  {
       string name = 1;
       int32 age = 2;
   }

Step 2:
Generate code from this .proto file

Once you have a .proto, the next step you need to do is generate the classes you'll need to read and write Student messages.

For this, you need to run the protocol buffer compiler protoc on your Student.proto

(check out this page for downloading: https://developers.google.com/protocol-buffers/docs/downloads)

Command:

protoc --go_out=. Student.proto

we had a option to generate the code specific to selected languages (such as Go, Java etc.) But, you need to download Go packages

**Step 3: ** Now Use the Go protocol buffer API to write and read messages.

create main.go and import "fmt" and "protocol buffer" packages

import (
    "fmt"
    proto "github.com/golang/protobuf/proto"
)

Create a variable for struct Student, fill-in value Marshal and Unmarshal and see the result

Run the program by linking the generated code go run main.go Student.pb.go

High Level Summary :

  1. Create Message using Protocol Buffer in .proto file

  2. Generate code from this .proto file

  3. Write server program

  4. Write client program

  5. Run server

  6. Run client

Did you find this article valuable?

Support Ashok V by becoming a sponsor. Any amount is appreciated!