golang gRPC 实践

says_rpc.proto

syntax = "proto2";

option cc_generic_services = true;
option java_generic_services = true;
option py_generic_services = true;

package says_rpc;

option go_package = "pb_models/says_rpc";


message RpcRequest {
    required string name = 1;
}

message RpcReply {
    required string message = 1;
}

service Greeter {
    rpc RpcCall(RpcRequest) returns (RpcReply) ;
}

rpc_server.go

package main

import (
   "context"
   "fmt"
   "google.golang.org/grpc"
   pb "gtest/src/pb_models/says_rpc"
   "log"
   "net"
   "protobuf/proto"
)

const(
   Port = ":50051"
)

type server struct {}

func (s *server) RpcCall(Ctx context.Context, In *pb.RpcRequest) (*pb.RpcReply, error) {
   log.Printf("Received : %v", In.GetName())
   Msg := fmt.Sprintf("Hello : %v " , In.GetName())
   return &pb.RpcReply{Message: proto.String(Msg)}, nil
}

func main() {
   Socket, Err := net.Listen("tcp", Port)
   if Err != nil {
      log.Fatalf("failed to listen : %v .", Err)
   }

   Rpc := grpc.NewServer()

   pb.RegisterGreeterServer(Rpc, &server{})

   if Err := Rpc.Serve(Socket); Err != nil {
      log.Fatalf("failed to service : %v .", Err)
   }
}

rpc_client.go

package main

import (
   "context"
   "google.golang.org/grpc"
   pb "gtest/src/pb_models/says_rpc"
   "log"
   "os"
   "protobuf/proto"
   "time"
)

const (
   Address = "localhost:50051"
   DefaultName = "ChengLin Gui"
)

func main() {

   Conn, Err := grpc.Dial(Address, grpc.WithInsecure())
   if Err != nil {
      log.Fatalf("did not connect : %v .", Err)
   }

   defer Conn.Close()

   Client := pb.NewGreeterClient(Conn)

   Name := DefaultName
   if len(os.Args) > 1 {
      Name = os.Args[1]
   }

   Ctx, Cancel := context.WithTimeout(context.Background(), time.Second)
   defer Cancel()
   RpcResult, RpcError := Client.RpcCall(Ctx, &pb.RpcRequest{Name : proto.String(Name)})
   if RpcError != nil {
      log.Fatalf("could not greet %v .", RpcError)
   }

   log.Printf("Greeting: %v .", RpcResult.GetMessage())
}

 

 

你可能感兴趣的:(golang,grpc,grpc,golang,golang)