查看来自grpc-go的helloworld示例,如何添加StopGrpcServer()
函数来停止gRPC服务器?
我正在尝试制作gRPC服务器的共享C库文件,该文件可通过通过ffi调用函数来启动和停止gRPC服务器。
在我的测试中,我能够使用StartGrpcServer()
启动gRPC服务器,但是我感到迷失了如何实现StopGrpcServer()
。
package main
import C
import (
"context"
"log"
"net"
"google.golang.org/grpc"
pb "google.golang.org/grpc/examples/helloworld/helloworld"
)
const (
port = ":50051"
)
// server is used to implement helloworld.GreeterServer.
type server struct {
pb.UnimplementedGreeterServer
}
// SayHello implements helloworld.GreeterServer
func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
log.Printf("Received: %v", in.GetName())
return &pb.HelloReply{Message: "Hello " + in.GetName()}, nil
}
//export StopGrpcServer
func (s *server) StopGrpcServer() {
s.Stop()
}
//export StartGrpcServer
func StartGrpcServer() {
lis, err := net.Listen("tcp", port)
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
s := grpc.NewServer()
pb.RegisterGreeterServer(s, &server{})
if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}
func main() {}
非常感谢您的帮助。谢谢,
饱和度
最佳答案
感谢@Marc的提示。我可以通过在*grpc.Server
之外全局声明StartGrpcServer()
变量,然后在StopGrpcServer()
中使用它来解决此问题。
这是工作代码:
package main
import C
import (
"context"
"log"
"net"
"google.golang.org/grpc"
pb "google.golang.org/grpc/examples/helloworld/helloworld"
)
var srv *grpc.Server
const (
port = ":50051"
)
// server is used to implement helloworld.GreeterServer.
type server struct {
pb.UnimplementedGreeterServer
}
// SayHello implements helloworld.GreeterServer
func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
log.Printf("Received: %v", in.GetName())
return &pb.HelloReply{Message: "Hello " + in.GetName()}, nil
}
//export StopGrpcServer
func StopGrpcServer() {
srv.Stop()
}
//export StartGrpcServer
func StartGrpcServer() {
lis, err := net.Listen("tcp", port)
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
srv = grpc.NewServer()
pb.RegisterGreeterServer(srv, &server{})
if err := srv.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}
func main() {}
// Compile with command:
// go build -o greeter.so -buildmode=c-shared server.go