定义proto文件
syntax = "proto3";
option go_package=".;proto";
// 普通proto类型
message HelloRequest {
string name = 1; // 1是编号不是值
}
message HelloResponse {
string reply = 1;
}
// rpc
service Hello{
rpc SayHello(HelloRequest) returns (HelloResponse);
}
生成go proto代码,类型和grpc代码
// 进入proto目录
protoc --go_out=. --go-grpc_out=. helloword.proto
server端注册rpc服务
-注意新grpc版本需要加 proto.UnimplementedHelloServer 来实现服务端stub接口
type Hello struct {
proto.UnimplementedHelloServer
}
func (h *Hello) SayHello(ctx context.Context, request *proto.HelloRequest) (*proto.HelloResponse, error) {
fmt.Println(request.Name)
return &proto.HelloResponse{
Reply: "hello " + request.Name,
}, nil
}
func main() {
s := grpc.NewServer()
// 注册HelloServer
proto.RegisterHelloServer(s, &Hello{})
listen, _ := net.Listen("tcp", ":8080")
if err := s.Serve(listen); err != nil {
panic(err)
}
}
client端调用代码
func main() {
dial, err := grpc.Dial("127.0.0.1:8080", grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
panic(err)
}
h := proto.NewHelloClient(dial)
helloRes, err := h.SayHello(context.Background(), &proto.HelloRequest{Name: "grpc"})
if err != nil {
panic(err)
}
fmt.Println(helloRes.Reply)
}