go超时控制-context包

335 阅读1分钟

channel

func main() {

	ch := make(chan struct{})

	http.HandleFunc("/test", func(writer http.ResponseWriter, request *http.Request) {

		go func() {

			for {
				time.Sleep(time.Second * 2)
				fmt.Println("123")
				ch <- struct{}{}
			}
		}()

		ch <- struct{}{}
		writer.Write([]byte("hello yu"))
	})

	log.Fatal(http.ListenAndServe(":8080", nil))
}

不能退出-只会阻塞到 ch <- struct{}{} 里面

使用 Context

http.HandleFunc("/test", func(writer http.ResponseWriter, request *http.Request) {

		go func() {
			for {
				select {
				case <-request.Context().Done():
					fmt.Println("已结束")
					return
				default:
					time.Sleep(time.Second * 2)
					fmt.Println("123")
				}
			}
		}()

		writer.Write([]byte("hello yu"))
	})

	log.Fatal(http.ListenAndServe(":8080", nil))

context包用法

ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
	defer cancel()

	for {
		select {
		case <-ctx.Done():
			fmt.Println(ctx.Err().Error()) //context deadline exceeded
			return
		default:
			time.Sleep(time.Second * 2)
			fmt.Println(123)
		}

	}

规定此段程序执行时间3s钟.

www.jianshu.com/p/e5df3cd07…

leileiluoluo.com/posts/golan…

studygolang.com/articles/13…

www.cnblogs.com/zhangboyu/p…