我正在尝试使用grpc-gateway在同一端口上的 GRPC 服务器上设置 rpc 服务器和代理 HTTP 服务器。奇怪的是,有时我会failed to receive server preface within timeout
随机出错。大多数情况下,它发生在服务重新启动时。它开始工作并在重试几次后返回正确的响应。我不确定发生了什么。有人可以帮帮我吗?这是服务启动片段
func makeHttpServer(conn *grpc.ClientConn) *runtime.ServeMux {
router := runtime.NewServeMux()
if err := services.RegisterHealthServiceHandler(context.Background(), router, conn); err != nil {
log.Logger.Error("Failed to register gateway", zap.Error(err))
nricher
if err := services.RegisterConstraintsServiceHandler(context.Background(), router, conn); err != nil {
log.Logger.Error("Failed to register gateway", zap.Error(err))
}
return router
}
func makeGrpcServer(address string) (*grpc.ClientConn, *grpc.Server) {
grpcServer := grpc.NewServer()
services.RegisterHealthServiceServer(grpcServer, health.Svc{})
services.RegisterABCServer(grpcServer, ABC.Svc{})
conn, err := grpc.DialContext(
context.Background(),
address,
grpc.WithInsecure(),
)
if err != nil {
log.Logger.Error("Failed to dial server", zap.Error(err))
}
return conn, grpcServer
}
func httpGrpcRouter(grpcServer *grpc.Server, httpHandler *runtime.ServeMux, listener net.Listener) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.ProtoMajor == 2 {
grpcServer.Serve(listener)
} else {
httpHandler.ServeHTTP(w, r)
}
})
}
func Start() error {
conf := config.Get()
address := fmt.Sprintf("%s:%d", conf.ServerHost, conf.ServerPort)
listener, err := net.Listen("tcp", address)
if err != nil {
log.Logger.Fatal("failed to listen: %v", zap.Error(err))
}
conn, grpcServer := makeGrpcServer(address)
router := makeHttpServer(conn)
log.Logger.Info("Starting server on address : " + address)
err = http.Serve(listener, httpGrpcRouter(grpcServer, router, listener))
return err
}