|
protobuf
syntax = "proto3";package pb;option go_package = "./;pb";message Person{ int32 age = 1; string name = 2;}service PersonService{ rpc Say(Person) returns (Person);}服务端
package mainimport ( "context" "fmt" "google.golang.org/grpc" "net" pb "pb_demo")type Person struct {}func (this *Person) Say(ctx context.Context, request *pb.Person) (*pb.Person, error) { request.Name = request.Name + "说:我要看世界!" return request,nil}func main() { // 实例化一个grpc服务 myGrpc := grpc.NewServer() // 注册服务 pb.RegisterPersonServiceServer(myGrpc, new(Person)) // 监听服务 listener, err := net.Listen("tcp", "127.0.0.1:8848") if err != nil { fmt.Println(err) return } _ = myGrpc.Serve(listener)}客户端
package mainimport ( "context" "fmt" "google.golang.org/grpc" pb "pb_demo")func main() { // 链接服务器端 conn, err := grpc.Dial("127.0.0.1:8848", grpc.WithInsecure()) if err != nil { fmt.Println(err) return } person := pb.NewPersonServiceClient(conn) request := &pb.Person{ Age: 10, Name: "杜甫", } ctx := context.Context(context.Background()) result, err := person.Say(ctx, request) if err != nil { fmt.Println(err) return } fmt.Println("client result: ", result)} |
|