grpc服务没有实现reflection.GRPCServer。

huangapple go评论84阅读模式
英文:

grpc service does not implement reflection.GRPCServer

问题

我正在创建一个使用Go语言的gRPC服务,我设置了以下的gRPC配置:

func setupGrpc() {
    lis, err := net.Listen("tcp", ":9000")
    if err != nil {
        log.Fatalf("failed to listen: %v", err)
    }

    s := followerservice.UserServer{}

    grpcServer := grpc.NewServer()
    gen.RegisterUserServiceServer(grpcServer, &s)

    // 为了方便命令行开发
    reflection.Register(s) // 这行代码不起作用!

    if err := grpcServer.Serve(lis); err != nil {
        log.Fatalf("failed to serve: %s", err)
    }
}

我的UserServer代码如下:

type UserServer struct {
    gen.UnimplementedUserServiceServer
}

func (s *UserServer) Create(ctx context.Context, in *gen.CreateUserRequest) (*gen.CreateUserResponse, error) {
    log.Printf("从客户端接收到消息体:%s", in.Email)
    return &gen.CreateUserResponse{Id: "新的ID!"}, nil
}

func setupGrpc()中标记的那一行,我得到了一个编译时错误:

followerservice.UserServer没有实现reflection.GRPCServer(缺少GetServiceInfo方法)

但是我找不到如何实现它,我已经搜索了几个小时了。感觉像是protoc可以为我生成这个方法,但我有点困惑。

英文:

I am creating a grpc service in go, I set up my grpc as follows

func setupGrpc() {
    lis, err := net.Listen("tcp", ":9000")
    if err != nil {
    	log.Fatalf("failed to listen: %v", err)
    }

    s := followerservice.UserServer{}

    grpcServer := grpc.NewServer()
    gen.RegisterUserServiceServer(grpcServer, &s)

    // for ease of cli dev
    reflection.Register(s) // this doesn't work!

    if err := grpcServer.Serve(lis); err != nil {
	    log.Fatalf("failed to serve: %s", err)
    }
}

My UserServer looks like this

type UserServer struct {
    gen.UnimplementedUserServiceServer
}

func (s *UserServer) Create(ctx context.Context, in *gen.CreateUserRequest)(*gen.CreateUserResponse, error) {
    log.Printf("Receive message body from client: %s", in.Email)
    return &gen.CreateUserResponse{Id: "new id!"}, nil
}

At the line marked in func setupGrpc() I get a compile time error:

> followerservice.UserServer does not implement reflection.GRPCServer (missing GetServiceInfo method)

but I can't find out how to implement it, I've been googling for hours now. It feels like protoc could generate this for me, but I'm kinda confused.

答案1

得分: 2

你需要对从grpc.NewServer()构造函数获得的*grpc.Server进行reflection.Register注册,而不是你自己的实现。

grpcServer := grpc.NewServer()
gen.RegisterUserServiceServer(grpcServer, &s)

reflection.Register(grpcServer)
英文:

You have to reflection.Register the *grpc.Server that you got from the grpc.NewServer() constructor, not your own implementation.

    grpcServer := grpc.NewServer()
    gen.RegisterUserServiceServer(grpcServer, &s)

    reflection.Register(grpcServer)

huangapple
  • 本文由 发表于 2022年10月24日 20:23:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/74181044.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定