Gracefully shutdown 이란 말은 좀 잘만든거 같음 적어도 Good Shutdown 보다는 낫자나
그래서 Gracfully Shutdown 이 뭐냐?
서버에서 돌아가는 OS 나 소프트웨어가 꺼질때 안전하게 끄는것
(A graceful shutdown is when a computer is turned off by software function and the operating system (OS)
is allowed to perform its tasks of safely shutting down processes and closing connections)
읭? 이게 뭔 소리
예를 들어 유튜브를 운영하는 백엔드 서버가 있다고 가정해보자
유튜브에서 야심차게 새로운 기능을 넣어서 (박)새로이 배포하려고 한다
유튜브 서버에서 금일 12시에 중단 배포를 진행하겠다고 한다.
하지만 유튜버인 나는 오늘 11시 55분에 2시간짜리 동영상을 올려야 겠다.
서버를 12시에 중단해서 내가 올린 2시간 짜리 동영상은 인코딩 중이었는데 서버가 중단되서 데이터가 다 날라가 버렸다.
유튜브에 소송 걸어서 승리해서 100억대 부자가 되었다.
끝
이면 좋겠지만 아쉽게도 상대는 유튜브다.
Gracefully Shutdown 을 적용하게 되면 서버를 중단시키기전에 해당하는 모든 작업을 종료하기 전까지는 서버가 Shutdown 되지 않는다. 이 위대한 종료는 golang 에만 국한되는게 아니다. Gracefully Shutdown 이 golang 에만 적용된다면 모두가 golang 쓰지 않을까? ( 바램 )
구현방법은 Golang 에서 http 패키지에 Graceful Shutdown 기능도 있기 때문에 아주 간단하다.
srv := &http.Server{
Handler: r,
Addr: fmt.Sprintf(":%s", config.GetString("PORT")),
ReadTimeout: 150 * time.Second,
WriteTimeout: 150 * time.Second,
}
우리가 원하는 Server config 를 구성하고
go func() {
log.Printf("Starting Server: http://127.0.0.1:%s", config.GetString("PORT"))
if err := srv.ListenAndServe(); err != nil {
log.Fatal(err)
}
}()
고루틴으로 서버를 연후
err := srv.Shutdown(context.Background())
if err != nil {
return
}
Shutdown 메서드를 호출하고 Context 만 넣으면 완벽하게는 아니지만 어느정도 우리가 원하는 방향(?)대로 구현이 되게 된다.
Custom Context 와 Signal 채널로 제어하면 더욱 서버에 맞는 , 서비스에 맞는 Graceful Shutdown 을 구현할 수 있을 것이다.
Golang http shutdown function detail
Shutdown gracefully shuts down the server without interrupting any active connections.
Shutdown works by first closing all open listeners, then closing all idle connections,
and then waiting indefinitely for connections to return to idle and then shut down.
If the provided context expires before the shutdown is complete, Shutdown returns the context's error,
otherwise it returns any error returned from closing the Server's underlying Listener(s).
When Shutdown is called, Serve, ListenAndServe, and ListenAndServeTLS immediately return ErrServerClosed.
Make sure the program doesn't exit and waits instead for Shutdown to return.
Shutdown does not attempt to close nor wait for hijacked connections such as WebSockets.
The caller of Shutdown should separately notify such long-lived connections of shutdown
and wait for them to close, if desired.
See RegisterOnShutdown for a way to register shutdown notification functions.
Once Shutdown has been called on a server, it may not be reused;
future calls to methods such as Serve will return ErrServerClosed.
'Go' 카테고리의 다른 글
고에서 에러 제어 (0) | 2022.06.08 |
---|---|
golang 구글 Oauth 인증 구현 (0) | 2022.05.17 |
Golang TDD (테스트 주도 개발) 유닛테스트 루트 절대경로 설정 (0) | 2022.04.08 |
고(golang) 메일보내기(google) (0) | 2022.01.13 |
고(golang) Context 겉핥기#3 (0) | 2022.01.10 |