|
| 1 | +/* |
| 2 | + * |
| 3 | + * Copyright 2024 gRPC authors. |
| 4 | + * |
| 5 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | + * you may not use this file except in compliance with the License. |
| 7 | + * You may obtain a copy of the License at |
| 8 | + * |
| 9 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | + * |
| 11 | + * Unless required by applicable law or agreed to in writing, software |
| 12 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | + * See the License for the specific language governing permissions and |
| 15 | + * limitations under the License. |
| 16 | + */ |
| 17 | + |
| 18 | +// Binary server demonstrates how to gracefully stop a gRPC server. |
| 19 | +package main |
| 20 | + |
| 21 | +import ( |
| 22 | + "context" |
| 23 | + "flag" |
| 24 | + "fmt" |
| 25 | + "log" |
| 26 | + "net" |
| 27 | + "os" |
| 28 | + "os/signal" |
| 29 | + "syscall" |
| 30 | + "time" |
| 31 | + |
| 32 | + "google.golang.org/grpc" |
| 33 | + pb "google.golang.org/grpc/examples/helloworld/helloworld" |
| 34 | +) |
| 35 | + |
| 36 | +var port = flag.Int("port", 50052, "port number") |
| 37 | + |
| 38 | +// server is used to implement helloworld.GreeterServer. |
| 39 | +type server struct { |
| 40 | + pb.UnimplementedGreeterServer |
| 41 | +} |
| 42 | + |
| 43 | +// SayHello implements helloworld.GreeterServer. |
| 44 | +func (s *server) SayHello(_ context.Context, _ *pb.HelloRequest) (*pb.HelloReply, error) { |
| 45 | + return &pb.HelloReply{Message: "Hello"}, nil |
| 46 | +} |
| 47 | + |
| 48 | +func main() { |
| 49 | + flag.Parse() |
| 50 | + |
| 51 | + address := fmt.Sprintf(":%v", *port) |
| 52 | + lis, err := net.Listen("tcp", address) |
| 53 | + if err != nil { |
| 54 | + log.Fatalf("failed to listen: %v", err) |
| 55 | + } |
| 56 | + |
| 57 | + // Create a channel to listen for OS signals. |
| 58 | + stop := make(chan os.Signal, 1) |
| 59 | + signal.Notify(stop, os.Interrupt, syscall.SIGTERM) |
| 60 | + |
| 61 | + s := grpc.NewServer() |
| 62 | + pb.RegisterGreeterServer(s, &server{}) |
| 63 | + |
| 64 | + go func() { |
| 65 | + // Wait for an OS signal for graceful shutdown. |
| 66 | + <-stop |
| 67 | + fmt.Println("Shutting down server...") |
| 68 | + s.GracefulStop() |
| 69 | + close(stop) |
| 70 | + }() |
| 71 | + |
| 72 | + if err := s.Serve(lis); err != nil { |
| 73 | + log.Fatalf("failed to serve: %v", err) |
| 74 | + } |
| 75 | + |
| 76 | + ctx, cancel := context.WithTimeout(context.Background(), time.Second) |
| 77 | + defer cancel() |
| 78 | + |
| 79 | + select { |
| 80 | + case <-stop: |
| 81 | + log.Printf("Server stopped gracefully") |
| 82 | + case <-ctx.Done(): |
| 83 | + log.Printf("Graceful stop timeout reached. Forcing server stop.") |
| 84 | + s.Stop() // Forceful stop |
| 85 | + } |
| 86 | +} |
0 commit comments