gRPC goLang tutorial with examples
- Get link
- X
- Other Apps
gRPC (Google Remote Procedure Call) एक ओपन-सोर्स, हाई-परफॉर्मेंस, और लाइटवेट RPC (Remote Procedure Call) फ्रेमवर्क है। यह विशेष रूप से माइक्रोसर्विसेज़ के बीच संचार के लिए उपयोगी है और डेटा को तेज़ी से और कुशलतापूर्वक संचारित करने में सक्षम है। gRPC HTTP/2 पर आधारित होता है और यह Protocol Buffers (protobuf) का उपयोग करता है, जो डेटा को सीरियलाइज़ और डीसिरियलाइज़ करने का एक अत्यधिक कुशल तरीका है।
यह ट्यूटोरियल gRPC के साथ एक सिंपल GoLang एप्लिकेशन बनाने के बारे में है।
gRPC GoLang Tutorial (हिंदी में)
Step 1: GoLang और gRPC की सेटअप करें
GoLang को इंस्टॉल करें:
- अगर आपके पास GoLang पहले से इंस्टॉल नहीं है तो GoLang डाउनलोड पेज से Go को इंस्टॉल करें।
gRPC और Protocol Buffers (protobuf) को इंस्टॉल करें:
gRPC के लिए आपको gRPC-Go पैकेज और protobuf को इंस्टॉल करना होगा।
gRPC-Go पैकेज इंस्टॉल करें:
go get google.golang.org/grpc
Protocol Buffers इंस्टॉल करें:
- सबसे पहले आपको Protocol Buffers Compiler (
protoc
) को इंस्टॉल करना होगा। प्रोटोकॉल बफ़र डाउनलोड पेज से डाउनलोड करें और इंस्टॉल करें। - फिर, Go के लिए gRPC प्लगइन इंस्टॉल करें:
go install google.golang.org/protobuf/cmd/protoc-gen-go@latest go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest
- सबसे पहले आपको Protocol Buffers Compiler (
Step 2: gRPC सर्विस डिफाइन करना
सबसे पहले, हमें एक .proto
फाइल बनानी होगी जिसमें हम अपनी gRPC सर्विस की डिफिनिशन करेंगे।
1. Proto फाइल बनाएं (service.proto)
service.proto
फाइल को अपने प्रोजेक्ट के डिरेक्टरी में बनाएं:
syntax = "proto3"; package user; service UserService { rpc GetUser (UserRequest) returns (UserResponse); rpc CreateUser (UserRequest) returns (UserResponse); } message UserRequest { string name = 1; int32 age = 2; } message UserResponse { string message = 1; string name = 2; int32 age = 3; }
यहाँ, हमने UserService
नामक एक सेवा डिफाइन की है, जिसमें दो RPCs (Methods) हैं:
GetUser
: एक यूज़र के बारे में जानकारी प्राप्त करने के लिए।CreateUser
: एक नया यूज़र बनाने के लिए।
Step 3: gRPC सर्वर और क्लाइंट को जनरेट करें
अब, protoc
कमांड का उपयोग करके Go कोड जनरेट करें:
protoc --go_out=. --go-grpc_out=. service.proto
यह कमांड .proto
फाइल से Go कोड जनरेट करेगी। इसमें service.pb.go
और service_grpc.pb.go
फाइलें शामिल होंगी। ये फाइलें gRPC सर्वर और क्लाइंट के लिए आवश्यक कोड प्रदान करेंगी।
Step 4: gRPC सर्वर को सेटअप करना
अब हम गRPC सर्वर बनाएंगे जो UserService
को इम्प्लीमेंट करेगा।
server.go फाइल बनाएँ:
package main
import (
"context"
"fmt"
"log"
"net"
"user"
"google.golang.org/grpc"
)
// UserServiceServer सर्विस का स्ट्रक्चर
type UserServiceServer struct {
user.UnimplementedUserServiceServer
}
// GetUser मेथड
func (s *UserServiceServer) GetUser(ctx context.Context, req *user.UserRequest) (*user.UserResponse, error) {
// कस्टम लॉजिक (यहां हम एक hardcoded response भेज रहे हैं)
return &user.UserResponse{
Message: "User data fetched successfully!",
Name: req.Name,
Age: req.Age,
}, nil
}
// CreateUser मेथड
func (s *UserServiceServer) CreateUser(ctx context.Context, req *user.UserRequest) (*user.UserResponse, error) {
// कस्टम लॉजिक (यहां हम एक hardcoded response भेज रहे हैं)
return &user.UserResponse{
Message: "User created successfully!",
Name: req.Name,
Age: req.Age,
}, nil
}
func main() {
// सर्वर की शुरुआत करें
lis, err := net.Listen("tcp", ":50051")
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
// gRPC सर्वर बनाएं
grpcServer := grpc.NewServer()
// सर्विस रजिस्टर करें
user.RegisterUserServiceServer(grpcServer, &UserServiceServer{})
// सर्वर को चलाएं
fmt.Println("gRPC server is running at port :50051")
if err := grpcServer.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}
GetUser
औरCreateUser
RPCs को सर्वर में इम्प्लीमेंट किया गया है।gRPC
सर्वरlocalhost:50051
पर चल रहा है।
Step 5: gRPC क्लाइंट सेटअप करना
अब हम gRPC क्लाइंट बनाएंगे जो सर्वर से कनेक्ट करेगा और RPC कॉल करेगा।
client.go फाइल बनाएँ:
gopackage main
import (
"context"
"fmt"
"log"
"user"
"google.golang.org/grpc"
)
func main() {
// gRPC सर्वर से कनेक्ट करें
conn, err := grpc.Dial(":50051", grpc.WithInsecure())
if err != nil {
log.Fatalf("did not connect: %v", err)
}
defer conn.Close()
// UserServiceClient बनाएं
client := user.NewUserServiceClient(conn)
// CreateUser RPC कॉल करें
req := &user.UserRequest{Name: "John Doe", Age: 30}
resp, err := client.CreateUser(context.Background(), req)
if err != nil {
log.Fatalf("could not create user: %v", err)
}
fmt.Println("Response:", resp.Message)
// GetUser RPC कॉल करें
resp2, err := client.GetUser(context.Background(), req)
if err != nil {
log.Fatalf("could not get user: %v", err)
}
fmt.Println("Response:", resp2.Message)
}
- क्लाइंट
localhost:50051
पर सर्वर से कनेक्ट होता है औरCreateUser
औरGetUser
RPCs को कॉल करता है।
Step 6: सर्वर और क्लाइंट को चलाएं
सबसे पहले सर्वर को चलाएं:
bashgo run server.go
अब क्लाइंट को चलाएं:
bashgo run client.go
यदि सब कुछ सही है, तो आपको सर्वर से रिस्पांस मिलेगा और क्लाइंट पर निम्नलिखित आउटपुट दिखाई देगा:
makefileResponse: User created successfully!
Response: User data fetched successfully!
Step 7: Dockerize करें (वैकल्पिक)
अगर आप चाहें तो इस एप्लिकेशन को Docker के माध्यम से कंटेनराइज कर सकते हैं। इसके लिए आपको Dockerfile
और docker-compose
की आवश्यकता होगी, ताकि सर्वर और क्लाइंट दोनों कंटेनर में चल सकें।
निष्कर्ष
इस ट्यूटोरियल में, हमने gRPC का उपयोग करके एक GoLang सर्वर और क्लाइंट बनाया। हमने सर्वर पर RPCs को इम्प्लीमेंट किया और क्लाइंट से gRPC सर्वर को कॉल किया। यह एक बुनियादी उदाहरण है, और आप इसे बड़े एप्लिकेशन में बढ़ा सकते हैं, जैसे कि माइक्रोसर्विसेज़ के बीच इंटर-प्रोसेस कम्युनिकेशन या अत्यधिक परफॉर्मेंट नेटवर्किंग के लिए।
gRPC के बारे में अधिक जानकारी के लिए gRPC डॉक्यूमेंटेशन को पढ़ें।
You said:
ChatGPT said:
In this tutorial, we will build a simple gRPC server and client using GoLang. The application will simulate a basic User Service that allows creating a user and fetching user data. The communication between the server and the client will use gRPC.
gRPC GoLang Tutorial with Examples
Step 1: Install Prerequisites
Before you start, ensure that the following tools are installed:
Go: Install Go (version 1.18 or later) from the official Go website: https://golang.org/dl/.
Protocol Buffers (protoc): Protocol Buffers are used by gRPC for serialization. Install the protobuf compiler from: https://github.com/protocolbuffers/protobuf/releases.
gRPC Go module: We need the gRPC Go libraries. You can install them with
go get
as shown below.bashgo get google.golang.org/grpc go get google.golang.org/protobuf/cmd/protoc-gen-go go get google.golang.org/grpc/cmd/protoc-gen-go-grpc
Step 2: Define Your Service in a .proto File
gRPC uses Protocol Buffers (protobuf) to define service methods and message types. Start by creating a user.proto
file:
user.proto:
protosyntax = "proto3"; package user; service UserService { rpc CreateUser (CreateUserRequest) returns (UserResponse); rpc GetUser (GetUserRequest) returns (UserResponse); } message CreateUserRequest { string name = 1; int32 age = 2; } message GetUserRequest { int32 id = 1; } message UserResponse { int32 id = 1; string name = 2; int32 age = 3; string message = 4; }
In this .proto
file:
UserService
defines two RPC methods:CreateUser
: Creates a new user.GetUser
: Fetches user data based on the user ID.
- The messages
CreateUserRequest
,GetUserRequest
, andUserResponse
define the structure of the data exchanged between the client and server.
Step 3: Generate Go Code from the .proto File
Next, use the protoc
compiler to generate Go code from your .proto
file.
Run the following command in the terminal:
bashprotoc --go_out=. --go-grpc_out=. user.proto
This command will generate two files:
user.pb.go
: Contains the message types.user_grpc.pb.go
: Contains the service client and server interfaces.
Step 4: Implement the gRPC Server
Now that we have the necessary Go code generated from the .proto
file, we can implement the server.
Create a file called server.go
:
gopackage main
import (
"context"
"fmt"
"log"
"net"
"user" // import the generated package
"google.golang.org/grpc"
)
type server struct {
user.UnimplementedUserServiceServer
}
// Implementing the CreateUser method
func (s *server) CreateUser(ctx context.Context, req *user.CreateUserRequest) (*user.UserResponse, error) {
// Simple logic for creating a user (using hardcoded data)
return &user.UserResponse{
Id: 1,
Name: req.Name,
Age: req.Age,
Message: "User created successfully!",
}, nil
}
// Implementing the GetUser method
func (s *server) GetUser(ctx context.Context, req *user.GetUserRequest) (*user.UserResponse, error) {
// Simple logic to return a user (using hardcoded data)
return &user.UserResponse{
Id: req.Id,
Name: "John Doe",
Age: 30,
Message: "User fetched successfully!",
}, nil
}
func main() {
// Set up a TCP listener
lis, err := net.Listen("tcp", ":50051")
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
// Create a new gRPC server
grpcServer := grpc.NewServer()
// Register the UserService with the server
user.RegisterUserServiceServer(grpcServer, &server{})
// Start the server
fmt.Println("gRPC server is running at port :50051")
if err := grpcServer.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}
In this file:
- The
CreateUser
andGetUser
methods are implemented, which are defined in the.proto
file. - The
UserServiceServer
is registered with the gRPC server. - The server listens on port
50051
for incoming requests.
Step 5: Implement the gRPC Client
Now, we’ll implement the client that will communicate with the server.
Create a file called client.go
:
gopackage main
import (
"context"
"fmt"
"log"
"user" // import the generated package
"google.golang.org/grpc"
)
func main() {
// Connect to the gRPC server
conn, err := grpc.Dial(":50051", grpc.WithInsecure()) // Connect to the server on port 50051
if err != nil {
log.Fatalf("could not connect: %v", err)
}
defer conn.Close()
// Create a new client for UserService
client := user.NewUserServiceClient(conn)
// Create a user
req := &user.CreateUserRequest{
Name: "Alice",
Age: 25,
}
resp, err := client.CreateUser(context.Background(), req)
if err != nil {
log.Fatalf("could not create user: %v", err)
}
fmt.Println("CreateUser Response:", resp.Message)
// Fetch user by ID
getReq := &user.GetUserRequest{Id: 1}
getResp, err := client.GetUser(context.Background(), getReq)
if err != nil {
log.Fatalf("could not get user: %v", err)
}
fmt.Println("GetUser Response:", getResp.Message)
}
In this file:
- The client connects to the gRPC server at
localhost:50051
. - It sends a
CreateUserRequest
to the server and prints the server's response. - It also sends a
GetUserRequest
to fetch the details of the user with ID1
.
Step 6: Run the Server and Client
First, run the server:
bashgo run server.go
The server should start running at
localhost:50051
.Then, in a new terminal, run the client:
bashgo run client.go
The client should send a request to the server, and you should see the output like this:
bashCreateUser Response: User created successfully! GetUser Response: User fetched successfully!
Step 7: Dockerize the Application (Optional)
To containerize the server and client using Docker, create a Dockerfile.
Dockerfile for the Server:
Dockerfile# Use the official Golang image FROM golang:1.18-alpine # Set the working directory WORKDIR /app # Copy the Go files into the container COPY . . # Install dependencies RUN go mod tidy # Build the Go application RUN go build -o server . # Expose the port the server runs on EXPOSE 50051 # Run the server CMD ["./server"]
Dockerfile for the Client:
Dockerfile# Use the official Golang image FROM golang:1.18-alpine # Set the working directory WORKDIR /app # Copy the Go files into the container COPY . . # Install dependencies RUN go mod tidy # Build the Go application RUN go build -o client . # Run the client CMD ["./client"]
You can build and run the Docker containers for the server and client as follows:
bashdocker build -t grpc-server -f Dockerfile.server .
docker build -t grpc-client -f Dockerfile.client .
docker run -d -p 50051:50051 grpc-server
docker run --rm grpc-client
Conclusion
You have now learned how to build a simple gRPC application in GoLang. We created a basic user service with two RPC methods: CreateUser
and GetUser
. The client communicates with the server using gRPC, sending requests and receiving responses.
This example can be expanded further by adding more features, using a real database, authentication, and more advanced error handling.
- Get link
- X
- Other Apps
Comments
Post a Comment