Go:grpc
发布时间:2020-12-16 09:24:09 所属栏目:大数据 来源:网络整理
导读:一、grpc安装 将 https: // github.com/google/go-genproto 放到 $GOPATH/src/google.golang.org/genproto 将 https: // github.com/grpc/grpc-go 放到 $GOPATH/src/google.golang.org/grpc 将 https: // github.com/golang/text 放到 $GOPATH/src/golang.or
一、grpc安装将 https://github.com/google/go-genproto 放到 $GOPATH/src/google.golang.org/genproto 将 https://github.com/grpc/grpc-go 放到 $GOPATH/src/google.golang.org/grpc 将 https://github.com/golang/text 放到 $GOPATH/src/golang.org/x/text 将 https://github.com/golang/net 放到 $GOPATH/src/golang.org/x/net 然后 cd $GOPATH/src/ go install google.golang.org/grpc PS:protobuf的安装不做介绍。 二、grpc的helloworld示例服务端: package main import ( "context" "log" "net" "google.golang.org/grpc" pb "google.golang.org/grpc/examples/helloworld/helloworld" ) const ( port = ":8080" ) // server用于实现helloworld.GreeterServer type server struct{} // SayHello实现了helloworld.GreeterServer func (s *server) SayHello(ctx context.Context,in *pb.HelloRequest) (*pb.HelloReply,error) { log.Printf("Received: %v",in.Name) return &pb.HelloReply{Message: "Hello " + in.Name},nil } func main() { // 监听 lis,err := net.Listen("tcp",port) if err != nil { log.Fatalf("failed to listen: %v",err) } // new服务对象 s := grpc.NewServer() // 注册服务 pb.RegisterGreeterServer(s,&server{}) if err := s.Serve(lis); err != nil { log.Fatalf("failed to serve: %v",err) } } 客户端: package main import ( "context" "log" "time" "google.golang.org/grpc" // 引用编译好的protobuf文件 pb "google.golang.org/grpc/examples/helloworld/helloworld" ) const ( address = "localhost:8080" name = "World" ) func main() { // 建立与服务器的连接 conn,err := grpc.Dial(address,grpc.WithInsecure()) if err != nil { log.Fatalf("连接失败: %v",err) } defer conn.Close() // 调用protobuf的函数创建客户端连接句柄 c := pb.NewGreeterClient(conn) ctx,cancel := context.WithTimeout(context.Background(),time.Second) defer cancel() // 调用protobuf的SayHello函数 r,err := c.SayHello(ctx,&pb.HelloRequest{Name: name}) if err != nil { log.Fatalf("调用SayHello失败: %v",err) } log.Println(r.Message) } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |