Syntax = "proto3";package hello;service ProductInfo { rpc say(HelloReq) returns (HelloResp);}message HelloReq { string ID = 1;}message HelloResp { string value = 1;}
2 实现gRPC运行时接口编解码支持库
go get -u github.com/golang/protobuf/proto
从 Proto文件(gRPC接口描述文件) 生成 go文件 的编译器插件
go get -u github.com/golang/protobuf/protoc-gen-go
获取go的gRPC包
go get Google.golang.org/grpc
生成代码
protoc --go_out=. *.proto
protoc --go_out=plugins=grpc:. ./hello/hello.proto
也可以知道其他目录
protoc --go_out=plugins=grpc:./msg2 ./hello/hello.proto
protoc -I ecommerce ecommerce/product_info.proto --go_out=plugins=grpc:./server/ecommerce
//option go_package="./;ecommerce";
—I 指定搜索目录,如果没有指定 –I 参数,则在当前目录进行搜索
--go_out=plugins=grpc:helloworld是输出目录
option go_package =“go/src/microtest/proto”;
为啥要定义reflection.Register(serv)客户端可以看到服务端的信息
grpcurl调用服务
grpcurl -plaintext localhost:8741 List
grpcurl -plaintext localhost:8741 describe Greeter
grpcurl -plaintext localhost:8741 describe grpc.reflection.v1Alpha.ServerReflection
grpcurl -plaintext localhost:8741 describe Greeter.SayHello
grpcurl -plaintext -d '{"name": "gopher"}' localhost:8741 Greeter.SayHello{ "message": "hello gopher"}grpcurl -plaintext -d @ localhost:8741 Greeter.SayHello{"name": "gopher"}
3 构建和运行 Syntax = "proto3";package ecommerce;service ProductInfo { rpc addProduct(Product) returns (ProductID); rpc getProduct(ProductID) returns (Product);}message Product { string ID = 1; string name = 2; string description = 3; float price = 4;}message ProductID { string value = 1;}
protoc -I ecommerce ecommerce/product_info.proto --go_out=plugins=grpc:./server/ecommerceprotoc -I ecommerce ecommerce/product_info.proto --go_out=plugins=grpc:./clIEnt/ecommerce
运行serveice
server通用的代码
lis, err := net.Listen("tcp", port) if err != nil { log.Fatalf("Failed to Listen: %v", err) } s := grpc.NewServer() pb.RegisterProductInfoServer(s, &server{}) if err := s.Serve(lis); err != nil { log.Fatalf("Failed to serve: %v", err) }
clIEnt通用的代码
// Set up a connection to the server. conn, err := grpc.Dial(address, grpc.WithInsecure()) if err != nil { log.Fatalf("dID not connect: %v", err) } defer conn.Close() c := pb.NewProductInfoClIEnt(conn) // Contact the server and print out its response. name := "Apple iPhone 11" description := "Meet Apple iPhone 11. All-new dual-camera system with ultra WIDe and Night mode." price := float32(699.00) ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() r, err := c.AddProduct(ctx, &pb.Product{name: name, Description: description, Price: price}) if err != nil { log.Fatalf("Could not add product: %v", err) } log.Printf("Product ID: %s added successfully", r.Value) product, err := c.GetProduct(ctx, &pb.ProductID{Value: r.Value}) if err != nil { log.Fatalf("Could not get product: %v", err) } log.Printf("Product: %v", product.String())
总结 以上是内存溢出为你收集整理的grpc(二)全部内容,希望文章能够帮你解决grpc(二)所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)