golang + grpc: register a service on GrpcServer

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

golang + grpc: register a service on GrpcServer

问题

我正在使用这个示例来构建一个Go语言的gRPC服务器。

但是似乎我漏掉了一些东西 - 在示例中有一个将服务注册到gRPC服务器的阶段,但是我的protoc输出中没有导出的注册方法:

s := grpc.NewServer()
pb.RegisterGreeterServer(s, &server{})

在protobuf3文件的编译中是否有变化?

我是否以错误的方式进行编译?

protoc --go_output=. *.proto

还有,我如何使服务在服务器上工作?目前它还没有:

func main() {
    lis, err := net.Listen("tcp", port)
    if err != nil {
        log.Fatalf("failed to listen: %v", err)
    }
    s := grpc.NewServer()
    // 注册应该放在这里吗?!
    reflection.Register(s)
    if err := s.Serve(lis); err != nil {
        log.Fatalf("failed to serve: %v", err)
    }
}
英文:

I'm working with this example for building a go lang grpc server.

But it seems that I'm missing something - In the example there is a phase of registering a service to the grpc-server but my protoc output has no registration method exported:

s := grpc.NewServer()
pb.RegisterGreeterServer(s, &server{})

Was there a change in the compilation of protobuf3 files?

Am I'm compiling it in the wrong way?

protoc --go_output=. *.proto

And how can I make the service work for the server, It is currently not:

func main() {
	lis, err := net.Listen("tcp", port)
	if err != nil {
		log.Fatalf("failed to listen: %v", err)
	}
	s := grpc.NewServer()
	//register should go here?!
	reflection.Register(s)
	if err := s.Serve(lis); err != nil {
		log.Fatalf("failed to server: %v", err)
	}
}

答案1

得分: 8

是的。正如Wendy Adi评论中指出的那样,protoc的命令行选项应该是--go_out而不是--go_output,同时还需要添加plugins=grpc选项(根据codegen.sh脚本的要求)。你可以使用protoc命令重新生成helloworld示例中的.pb.go文件:

cd $GOPATH/src/google.golang.org/grpc/examples/helloworld
mv helloworld.pb.go helloworld.pb.go.orig
protoc --go_out=plugins=grpc:. helloworld.proto

之后,greeter_server应该能够正确编译:

cd ../greeter_server
go build .
英文:

> Am I'm compiling it in the wrong way?
>
> protoc --go_output=. *.proto

Yes. As pointed out in the comment by Wendy Adi, the command-line option to protoc should be --go_out not --go_output and the plugins=grpc option is needed as well (as per the codegen.sh script). You should be able to use protoc to regenerate the .pb.go file in the helloworld example:

cd $GOPATH/src/google.golang.org/grpc/examples/helloworld
mv helloworld.pb.go helloworld.pb.go.orig
protoc --go_out=plugins=grpc:. helloworld.proto

The greeter_server should compile correctly afterwards:

cd ../greeter_server
go build .

答案2

得分: 0

如果使用grpc 3,请使用以下命令:

protoc -I=proto --go_out=. --go-grpc_out=. proto/*.proto
英文:

if using grpc 3 use below cmd

protoc -I=proto --go_out=. --go-grpc_out=. proto/*.proto

huangapple
  • 本文由 发表于 2017年2月4日 21:29:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/42040951.html
匿名

发表评论

匿名网友

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

确定