go grpc中间件
go grpc中间件
本例为查询“计量单位”。
编辑 units.proto
syntax="proto3"; package main; message Units { string unitid = 1; string unitname = 2; } message Unitss { repeated Units UnitsArr = 1; } message UnitsRequest { string dbid = 1; } service UnitsService{ rpc UnitsQry(UnitsRequest) returns(Unitss); }
根据 units.proto自动生成go代码
protoc --gofast_out=plugins=grpc:./ ./units.proto
服务端
// svrgrpc project main.go //cxg 2021-9-25 package main import ( "fmt" "net" "context" "google.golang.org/grpc" ) type server struct{} func (s *server) UnitsQry(ctx context.Context, in *UnitsRequest) (*Unitss, error) { fmt.Println("request: ", in.Dbid) var u Units u.Unitid = "1" u.Unitname = "个" var us Unitss us.UnitsArr = append(us.UnitsArr, &u) return &us, nil } func main() { listen, err := net.Listen("tcp", ":7070") if err != nil { fmt.Println("failed to listen: %v", err) } s := grpc.NewServer() RegisterUnitsServiceServer(s, &server{}) fmt.Println("咏南grpc服务已经开启") s.Serve(listen) }
go客户端
// clientgrpc project main.go package main import ( "context" "fmt" "google.golang.org/grpc" ) const ( address = "localhost:7070" ) func main() { conn, err := grpc.Dial(address, grpc.WithInsecure()) if err != nil { fmt.Println("did not connect: %v", err) } defer conn.Close() c := NewUnitsServiceClient(conn) r, err := c.UnitsQry(context.Background(), &UnitsRequest{Dbid: "1"}) if err != nil { fmt.Println("could not greet: %v", err) } fmt.Println(r.UnitsArr[0].Unitid, r.UnitsArr[0].Unitname) }
凡支持gRPC客户端的其他语言都可以调用。
本文来自博客园,作者:{咏南中间件},转载请注明原文链接:https://www.cnblogs.com/hnxxcxg/p/15334930.html