gRPC uses HTTP/2 for transport and protocol Buffers as the interface description language. HTTP/2 is multiplexed and it can support multiple requests in parallel over a single TCP connection.
With gRPC we can define our service once in a .proto file and implement clients and servers.
Protocol buffers allow serialization and deserialization of structured data, with the goal to provide a faster way to make systems communicate due to optimized serialization and deserialization
Protobuf is a binary message format, and because it is in binary, serialization and de-serialization is fast and the size of the message is lower than JSON & XML.
Once you've defined your messages, you run the protocol buffer compiler for your application's language on your .proto file to generate data access classes for the client and server
Installation:
go get github.com/golang/protobuf/protoc-gen-go
export PATH="$PATH:$(go env GOPATH)/bin"
Working with grpc:
-
Define the datastructures(protocol buffer message types) and APIs required in the proto file
-
Once you've defined your messages, you run the protocol buffer compiler
To compile the proto file and generate code:
* install protoc-gen
* create a directory (chat) where we want the files generated by protoc to go into.
* Run the command to compile chat.proto and generate code
protoc --go_out=plugins=grpc:chat chat.proto
General syntax : protoc -I=$SRC_DIR --go_out=$DST_DIR $SRC_DIR/chat.proto
3 Implement the chat service
chat.go in package chat is the implementation of the ChatServer, the apis defined in proto file Uses the interface methods, register chat methods with grpc server
-
Start the grpc server to provide handlers for the services (apis) defined above (server.go)
Start grpc server In server.go -> The grpc server is started Listeners are added for chat service (register the chat service defined in the proto file)
-
Send messages to the server from a client:
client.go initializes a client and sends a message using the method defined in the proto file (sayHello) (Refer chat.pb.go for available methods and data structures)
- Streaming is possible using the multiplexing capability provided by http2
Server Streaming RPC: The client sends a single request and the server can send back multiple responses (Ex: The server fetches data in parts and returns it to client soon as it is available) Client Streaming RPC: Where the client sends multiple requests and the server only sends back a single response ( Ex. client uploads a large file in parts to the server) Bidirectional Streaming RPC: Where both the client and server send messages to each other at the same time without waiting for a response.
References