-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #32 from zjutjh/SugarMGP/dev
refactor: 实现优雅停止
- Loading branch information
Showing
2 changed files
with
52 additions
and
4 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
package server | ||
|
||
import ( | ||
"context" | ||
"errors" | ||
"net/http" | ||
"os" | ||
"os/signal" | ||
"time" | ||
|
||
"4u-go/config/redis" | ||
"go.uber.org/zap" | ||
) | ||
|
||
// Run 运行 http 服务器 | ||
func Run(handler http.Handler, addr string) { | ||
srv := &http.Server{ | ||
Addr: addr, | ||
Handler: handler, | ||
ReadHeaderTimeout: 2 * time.Second, | ||
} | ||
|
||
// 启动服务器协程 | ||
go func() { | ||
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { | ||
zap.L().Fatal("Server Error Occurred", zap.Error(err)) | ||
} | ||
}() | ||
|
||
// 阻塞并监听结束信号 | ||
quit := make(chan os.Signal, 1) | ||
signal.Notify(quit, os.Interrupt) | ||
<-quit | ||
|
||
zap.L().Info("Shutdown Server...") | ||
|
||
// 关闭服务器(5秒超时时间) | ||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) | ||
defer cancel() | ||
if err := srv.Shutdown(ctx); err != nil { | ||
zap.L().Error("Server Shutdown Failed", zap.Error(err)) | ||
} | ||
|
||
// 关闭 Redis 客户端 | ||
if err := redis.GlobalClient.Close(); err != nil { | ||
zap.L().Error("Redis Client Shutdown Failed", zap.Error(err)) | ||
} | ||
|
||
zap.L().Info("Server Closed") | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters