github.com/weedge/lib@v0.0.0-20230424045628-a36dcc1d90e4/client/etcd/cmd/discovery_server/main.go (about) 1 package main 2 3 import ( 4 "context" 5 "flag" 6 "fmt" 7 "github.com/weedge/lib/client/etcd/discovery" 8 "google.golang.org/grpc/keepalive" 9 "net" 10 "time" 11 12 "google.golang.org/grpc" 13 14 "github.com/weedge/lib/client/etcd/cmd/pb" 15 "github.com/weedge/lib/log" 16 ) 17 18 const defaultService = "test-service" 19 20 type helloService struct { 21 pb.UnimplementedHelloServer 22 } 23 24 func (h *helloService) Echo(ctx context.Context, req *pb.EchoRequest) (*pb.EchoRequest, error) { 25 fmt.Println(req.Message) 26 return req, nil 27 } 28 29 func (h *helloService) Stream(req *pb.EchoRequest, srv pb.Hello_StreamServer) error { 30 fmt.Println("stream", req.Message) 31 i := 1 32 for i < 5 { 33 if srv.Context().Err() != nil { 34 return srv.Context().Err() 35 } 36 37 err := srv.Send(req) 38 if err != nil { 39 return err 40 } 41 i++ 42 time.Sleep(time.Millisecond * 500) 43 } 44 return nil 45 } 46 47 var kaep = keepalive.EnforcementPolicy{ 48 MinTime: 5 * time.Second, // If a client pings more than once every 5 seconds, terminate the connection 49 PermitWithoutStream: true, // Allow pings even when there are no active streams 50 } 51 52 var kasp = keepalive.ServerParameters{ 53 MaxConnectionIdle: 15 * time.Second, // If a client is idle for 15 seconds, send a GOAWAY 54 MaxConnectionAge: 30 * time.Second, // If any connection is alive for more than 30 seconds, send a GOAWAY 55 MaxConnectionAgeGrace: 5 * time.Second, // Allow 5 seconds for pending RPCs to complete before forcibly closing connections 56 Time: 5 * time.Second, // Ping the client if it is idle for 5 seconds to ensure the connection is still active 57 Timeout: 1 * time.Second, // Wait 1 second for the ping ack before assuming the connection is dead 58 } 59 60 func main() { 61 port := flag.String("port", ":8080", "listen port") 62 service := flag.String("service", defaultService, "service name") 63 flag.Parse() 64 65 r := discovery.NewRegister([]string{"0.0.0.0:2379"}, 5*time.Second, *service, "localhost"+*port) 66 defer r.Close() 67 68 err := r.Do() 69 if err != nil { 70 log.Error(err.Error()) 71 } 72 73 lis, err := net.Listen("tcp", *port) 74 if err != nil { 75 panic(err) 76 } 77 78 s := grpc.NewServer(grpc.KeepaliveEnforcementPolicy(kaep), grpc.KeepaliveParams(kasp)) 79 80 pb.RegisterHelloServer(s, &helloService{}) 81 if err := s.Serve(lis); err != nil { 82 log.Errorf("failed to serve: %v", err) 83 } 84 85 }