gRPC(gRPC Remote Procedure Calls)是一个高性能、开源和通用的RPC框架,用于在分布式系统中实现跨机器和跨语言的通信。它基于HTTP/2协议,支持多种编程语言,并使用Protocol Buffers作为接口定义语言(IDL)。
gRPC支持多种服务类型:
原因:
解决方法:
原因:
解决方法:
解决方法:
以下是一个简单的gRPC服务端和客户端的示例代码:
package main
import (
"context"
"log"
"net"
"google.golang.org/grpc"
pb "path/to/your/proto"
)
type server struct {
pb.UnimplementedYourServiceServer
}
func (s *server) YourMethod(ctx context.Context, req *pb.YourRequest) (*pb.YourResponse, error) {
log.Printf("Received request: %v", req)
return &pb.YourResponse{Message: "Hello, " + req.Name}, nil
}
func main() {
lis, err := net.Listen("tcp", ":50051")
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
s := grpc.NewServer()
pb.RegisterYourServiceServer(s, &server{})
log.Printf("Server listening at %v", lis.Addr())
if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}
package main
import (
"context"
"log"
"time"
"google.golang.org/grpc"
pb "path/to/your/proto"
)
func main() {
conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure())
if err != nil {
log.Fatalf("did not connect: %v", err)
}
defer conn.Close()
c := pb.NewYourServiceClient(conn)
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
r, err := c.YourMethod(ctx, &pb.YourRequest{Name: "World"})
if err != nil {
log.Fatalf("could not greet: %v", err)
}
log.Printf("Response: %s", r.Message)
}
领取专属 10元无门槛券
手把手带您无忧上云