Skip to content

Commit

Permalink
1.增加RegisterOnRestart注册
Browse files Browse the repository at this point in the history
2.增加TERM/HUP信号量默认处理
  • Loading branch information
zirongwan committed Nov 20, 2020
1 parent f8b91ca commit f8f29e9
Showing 1 changed file with 23 additions and 6 deletions.
29 changes: 23 additions & 6 deletions server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ type Server struct {

inShutdown int32
onShutdown []func(s *Server)
onRestart []func(s *Server)

// TLSConfig for creating tls tcp connection.
tlsConfig *tls.Config
Expand Down Expand Up @@ -174,13 +175,22 @@ func (s *Server) startShutdownListener() {
go func(s *Server) {
log.Info("server pid:", os.Getpid())
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGTERM)
signal.Notify(c, syscall.SIGTERM, syscall.SIGHUP)
si := <-c
if si.String() == "terminated" {
if nil != s.onShutdown && len(s.onShutdown) > 0 {
for _, sd := range s.onShutdown {
sd(s)
}
var customFuncs []func(s *Server)
switch si.String() {
case "terminated":
customFuncs = append(s.onShutdown, func(s *Server) {
s.Shutdown(context.Background())
})
case "hangup":
customFuncs = append(s.onRestart, func(s *Server) {
s.Restart(context.Background())
})
}
if nil != customFuncs && len(customFuncs) > 0 {
for _, fn := range customFuncs {
fn(s)
}
}
}(s)
Expand Down Expand Up @@ -700,6 +710,13 @@ func (s *Server) RegisterOnShutdown(f func(s *Server)) {
s.mu.Unlock()
}

// RegisterOnRestart registers a function to call on Restart.
func (s *Server) RegisterOnRestart(f func(s *Server)) {
s.mu.Lock()
s.onRestart = append(s.onRestart, f)
s.mu.Unlock()
}

var shutdownPollInterval = 1000 * time.Millisecond

// Shutdown gracefully shuts down the server without interrupting any
Expand Down

0 comments on commit f8f29e9

Please sign in to comment.