Middle — Middle+
How was the integration and interaction of components carried out via gRPC in your project?
sobes.tech AI
Answer from AI
In my project, component integration via gRPC was carried out as follows:
- Defining services and messages in
.protofiles using Protocol Buffers. - Generating server and client code in Go using
protocand theprotoc-gen-goplugin. - Implementing the methods described in the services on the server side, with business logic.
- Clients called these methods through generated stub objects, ensuring type-safe and efficient interaction.
- To ensure reliability, contexts with timeouts were used, along with middleware for logging and authentication.
Example of a simple server and client in Go:
// server.go
import (
"context"
"net"
"google.golang.org/grpc"
pb "path/to/proto"
)
type server struct {
pb.UnimplementedMyServiceServer
}
func (s *server) MyMethod(ctx context.Context, req *pb.MyRequest) (*pb.MyResponse, error) {
// Implementation of the method
return &pb.MyResponse{Message: "Hello " + req.Name}, nil
}
func main() {
lis, _ := net.Listen("tcp", ":50051")
s := grpc.NewServer()
pb.RegisterMyServiceServer(s, &server{})
s.Serve(lis)
}
// client.go
import (
"context"
"time"
"google.golang.org/grpc"
pb "path/to/proto"
)
func main() {
conn, _ := grpc.Dial("localhost:50051", grpc.WithInsecure())
defer conn.Close()
client := pb.NewMyServiceClient(conn)
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
resp, err := client.MyMethod(ctx, &pb.MyRequest{Name: "World"})
if err != nil {
// handle error
}
fmt.Println(resp.Message)
}
Thus, gRPC provided efficient, strongly typed, and scalable interaction between microservices.