go http server graceful exit

本文介绍了如何在Go中实现HTTP服务器的优雅退出。通过一个测试实验,展示了在服务运行过程中,即使在6秒数据返回前停止服务,Go 1.8及更高版本的`server.Shutdown(context)`方法也能确保服务优雅关闭。实验提出疑问,对于`shutdown`函数中的`context`参数,应该传入`nil`、`Background()`还是其他值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天做了一个go语音的http server优雅退出的测试实验

package main

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
)

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		t:=time.NewTimer(6 * time.Second)
		L: for {
			time.Sleep(1*time.Second)
			select {
			case <- t.C:
				fmt.Println("\ntime out===============================")
				break L
			default:
				fmt.Println("i am doing job")
			}
		}
		fmt.Fprintf(w, "Hello World, %v\n", time.Now())
	})

	s := &http.Server{
		Addr:           ":8080",
		Handler:        http.DefaultServeMux,
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}

	go func() {
		log.Println(s.ListenAndServe())
		log.Println("server shutdown")
	}()

	// Handle SIGINT and SIGTERM.
	ch := make(chan os.Signal)
	signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
	log.Println(<-ch)

	// Stop the service gracefully.
	log.Println(s.Shutdown(context.Background()))

	// Wait gorotine print shutdown message
	log.Println("done.")
}

 

在正常访问服务的时候,会一直打印出 i am doing job, 并在6s之后返回数据

curl http://localhost:8080/

 

试一下,6s没到,就把服务给停掉,看服务能否优雅退出

服务还是能优雅退出

证明go1.8版本的 server.shutdown(context) 就考虑了优雅退出,只需要调用就好了

进一步需要思考的问题:在使用这个shutdown函数的时候这个context传什么?nil 还是Background()还是其他?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值