我的优雅停止http.ListenAndServe失败
我是一个新手去程序员 我正在编写一个web应用程序,我需要服务器等待活动请求发出后再关闭 我编写了一个等待5秒的处理程序。如果我发出请求并停止服务器(在5秒钟之前),我会收到“无法连接”错误 有没有一种方法可以停止侦听新请求并等待活动请求完成 这里是我的例子我的优雅停止http.ListenAndServe失败,http,go,Http,Go,我是一个新手去程序员 我正在编写一个web应用程序,我需要服务器等待活动请求发出后再关闭 我编写了一个等待5秒的处理程序。如果我发出请求并停止服务器(在5秒钟之前),我会收到“无法连接”错误 有没有一种方法可以停止侦听新请求并等待活动请求完成 这里是我的例子 func main(){ log.Infof(“正在启动(PID%d)…”,os.Getpid() 停止:=接通(切换操作信号,1) signal.Notify(stop,syscall.SIGTERM) signal.Notify(停止,
func main(){
log.Infof(“正在启动(PID%d)…”,os.Getpid()
停止:=接通(切换操作信号,1)
signal.Notify(stop,syscall.SIGTERM)
signal.Notify(停止,syscall.SIGINT)
列表:=“127.0.0.1:8000”
r:=newRouter()
h:=&http.Server{Addr:listenAt,Handler:r}
go func(){
log.Info(“在http://”上服务,listenAt)
如果错误:=h.ListenAndServe();错误!=nil{
log.Fatal(错误)
}
}()
一种方法是通过以下方式将最大连接数缩小到1:
l, err := net.Listen("tcp", ":8000")
if err != nil {
log.Fatalf("Listen: %v", err)
}
defer l.Close()
l = netutil.LimitListener(l, 1)
log.Fatal(http.Serve(l, nil))
另一种方法是使用全局变量:
package main
import (
"net/http"
"sync/atomic"
"fmt"
)
var toggle *int32
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
func handler(w http.ResponseWriter, r *http.Request) {
val := atomic.LoadInt32(toggle)
if val != 0 {
fmt.Fprintln(w, "Not Valid!")
w.WriteHeader(http.StatusForbidden)
return
}
atomic.StoreInt32(toggle, 1)
// do stuff
w.WriteHeader(http.StatusOK)
}
func init (){
atomic.StoreInt32(toggle, int32(0))
}
**请注意,这两种方法都适用于单节点服务器,而不适用于分布式系统,解决方案是使用缓存服务器,如redis等。由于这个和它们的示例,我找到了这个和它们的。我发现我的问题与net/http模块无关
真正的问题是log.Fatal(err)
内部的go func()
,将其更改为log.Info(err)
不会中止关机过程
go func() {
log.Info("Serving on http://", listenAt)
if err := h.ListenAndServe(); err != nil {
// log.Fatal(err)
log.Info(err)
}
}()
你能扩展你的解释吗?我理解你的建议,但我不能把它应用到我的例子中。谢谢。为第二种方法添加了代码片段