首页 > 其他分享 >golang context

golang context

时间:2022-10-17 17:01:20浏览次数:53  
标签:请求 goroutine ctx golang deadline context time

一、go标准库context

前言:

在 Go http包的Server中,每一个请求在都有一个对应的 goroutine 去处理。请求处理函数通常会启动额外的 goroutine 用来访问后端服务,比如数据库和RPC服务。用来处理一个请求的 goroutine 通常需要访问一些与请求特定的数据,比如终端用户的身份认证信息、验证相关的token、请求的截止时间。 当一个请求被取消或超时时,所有用来处理该请求的 goroutine 都应该迅速退出,然后系统才能释放这些 goroutine 占用的资源

二、with 函数如下

WithDeadline的函数签名如下

func WithDeadline(parent Context, deadline time.Time) (Context, CancelFunc)

案例:

func doTimeoutWort(ctx context.Context) {
	for {
		time.Sleep(time.Second)
		if deadline, ok := ctx.Deadline(); ok {
			fmt.Println("deadline set")
			//3秒后执行
			if time.Now().After(deadline) {
				fmt.Println(ctx.Err().Error())
				return
			}
		}
	}
}
func main() {
	//定义一个3秒后过期的deadline
	ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(3*time.Second))
	go doTimeoutWort(ctx)
	time.Sleep(7 * time.Second)
	cancel()
}

 

 

执行3秒后退出

标签:请求,goroutine,ctx,golang,deadline,context,time
From: https://www.cnblogs.com/wuchangblog/p/16799792.html

相关文章