在Go http包的Server中,每一个请求在都有一个对应的goroutine去处理。请求处理函数通常会启动额外的goroutine用来访问后端服务。比如数据库和RPC服务。用来处理一个请求的goroutine通常需要访问一些与请求特定的数据,比如终端用户的身份认证信息,验证相关的token,请求的截止时间。当一个请求被取消或超时时,所有用来处理请求的goroutine都应该迅速退出,然后系统才能释放这些goroutine占用的资源。
一. 为什么需要Context
使用示例来说明:
基本示例:
package main
import (
"fmt"
"sync"
"time"
)
var wg sync.WaitGroup
func work1() {
for {
fmt.Println("worker")
time.Sleep(time.Second)
}
wg.Done()
}
func main() {
wg.Add(1)
go work1()
wg.Wait()
fmt.Println("over")
}
怎么接受外部命令实现退出goroutine?
- 使用全局变量
使用全局变量存在的问题是:
1. 跨包调用时不容易统一
2. 如果使用work1中再启动一个goroutine,就不大好控制了
package main
import (
"fmt"
"sync"
"time"
)
var wg sync.WaitGroup
// 协程是否退出
var exit1 bool
func work1() {
for {
fmt.Println("worker")
time.Sleep(time.Second)
if exit1 {
break
}
}
wg.Done()
}
func main() {
wg.Add(1)
exit1 = false
go work1()
time.Sleep(time.Second * 3)
exit1 = true
wg.Wait()
fmt.Println("over")
}
- 通道方式
问题:使用全局变量在跨包调用时不容易实现规范和统一,需要维护一个共用的channel。
package main
import (
"fmt"
"sync"
"time"
)
var wg sync.WaitGroup
func work1(exitChan chan struct{}) {
LOOP:
for {
fmt.Println("worker")
time.Sleep(time.Second)
select {
case <-exitChan:
break LOOP //等待上级通知,退出循环
default:
}
}
wg.Done()
}
func main() {
var exitChan = make(chan struct{}) //为管道分配内存
wg.Add(1)
go work1(exitChan)
time.Sleep(time.Second * 3)
exitChan <- struct{}{} //给goroutine发消息
wg.Wait()
fmt.Println("over")
}
- 官方版
使用context
package main
import (
"context"
"fmt"
"sync"
"time"
)
var wg sync.WaitGroup
func work1(ctx context.Context) {
LOOP:
for {
fmt.Println("worker")
time.Sleep(time.Second)
select {
case <-ctx.Done():
break LOOP //等待上级通知,退出循环
default:
}
}
wg.Done()
}
func main() {
//context.Background()放回一个非nil的空context
//一般用于初始化和测试
ctx, cancel := context.WithCancel(context.Background())
wg.Add(1)
go work1(ctx)
time.Sleep(time.Second * 3)
//通知goroutine结束
cancel()
wg.Wait()
fmt.Println("over")
}
当子goroutine又开启一个goroutine时,只需要将ctx传入即可。
package main
import (
"context"
"fmt"
"sync"
"time"
)
var wg sync.WaitGroup
func work2(ctx context.Context) {
LOOP:
for {
fmt.Println("worker")
time.Sleep(time.Second)
select {
case <-ctx.Done():
break LOOP //等待上级通知,退出循环
default:
}
}
}
func work1(ctx context.Context) {
go work2(ctx)
LOOP:
for {
fmt.Println("worker")
time.Sleep(time.Second)
select {
case <-ctx.Done():
break LOOP //等待上级通知,退出循环
default:
}
}
wg.Done()
}
func main() {
//context.Background()放回一个非nil的空context
//一般用于初始化和测试
ctx, cancel := context.WithCancel(context.Background())
wg.Add(1)
go work1(ctx)
time.Sleep(time.Second * 3)
//通知goroutine结束
cancel()
wg.Wait()
fmt.Println("over")
}
二. Context初识
Go1.7加入了一个新的标准库context,他定义了Context类型,专门用来简化对于处理单个请求的多个goroutine之间与请求域的数据,取消信号,截止时间等相关操作,这些操作可能涉及多个API调用。
对服务器传入的请求应该创建上下文,而对服务器的传出调用应该接受上下文。他们之间的函数调用链必须传递上下文,或者可以使用WithCancel,WithDeadline,WithTimeout或WithValue创建的派生上下文。当一个上下文被取消时,它派生的所有上下文也被取消。
三. Context接口
context.Context是一个接口,该接口定义了四个需要实现的方法,具体签名如下:
type Context interface {
Deadline() (deadline time.Time, ok bool)
Done() <-chan struct{}
Err() error
Value(key interface{}) interface{}
}
其中:
- Deadline方法需要返回当前Context被取消的时间,也就是完成工作的截止时间(deadline)。
- Done方法需要返回一个Channel,这个Channel会在当前工作完成或者上下文被取消之后关闭,多次调用Done方法会返回同一个Channel。
- Err方法会返回当前Context结束的原因,它只会在Done返回的Channel被关闭时才会返回非空值:
- 如果当前Context被取消就会返回Canceled错误
- 如果当前Context超时就会返回DeadlineExceeded错误
- Value方法会从Context中返回键对应的值,对于同一个上下文来说,多次调用Value并传入相同的Key会返回相同的结果,该方法仅用于传递跨API和进程间跟请求域的数据。
四. Background()和TODO()
Go内置两个函数:Background()和TODO(),这两个函数分别返回一个实现Context接口的background和todo。我们代码中最开始的都是以这两个内置的上下文对象作为最顶层parent context,衍生出更多的子上下文。
Background()主要用于main函数,初始化以及测试代码中,作为Context这个树结构的最顶层Context,也就是根Context
TODO(),目前还不知道具体使用场景,如果我们不知道该使用什么Context的时候,可以使用这个。
background和todo本质都是emptyCtx结构体类型,是一个不可取消,没有设置截止时间,没有携带任何值的Context。
五. With系列函数
5.1 WithCancel
函数签名:
func WithCancel(parent Context) (ctx Context, cancel CancelFunc)
WithCancel返回带有新Done通道的父节点的副本,当调用返回的cancel函数或当关闭上下文的Done通道时,将关闭返回上下文的Done通道,无论发生什么情况。
取消上下文将释放与其关联的资源,因此代码应该在此上下文中运行操作完成后立即调用Done()。
package main
import (
"context"
"fmt"
)
func gen(ctx context.Context) <-chan int {
ch := make(chan int)
n := 1
//生成数字到ch,发送给main
go func() {
for {
select {
case <-ctx.Done():
return
case ch <- n:
n++
}
}
}()
return ch
}
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel() //取完需要的整数 调用cancel 释放上下文
for n := range gen(ctx) {
fmt.Println(n)
if n == 5 {
break
}
}
}
在上面示例代码中,gen函数在单独的goroutine中生成整数并将它们发送到返回的通道。gen的调用者(这里是main函数)在使用生成的整数之后需要需要上下文(cancel()函数),以免gen启动的内部goroutine发生泄漏。
5.2 WithDeadline
函数签名:
func WithDeadline(parent Context, deadline time.Time) (Context, CancelFunc)
返回上下文的副本,并将deadline调整为不迟于参数deadline。如果父上下文的deadline已经早于deadline,则WithDeadline(parent,d)在语义上等同于父上下文。
当截止日过期,当调用返回的cancel函数时,或者当父上下文的Done通道关闭时,返回上下文的Done通道将被关闭,以最先发生的情况为准。
取消上下文将释放与其关联的资源,因此代码应该在此上下文中运行的操作完成后立即调用cancel。
package main
import (
"context"
"fmt"
"time"
)
func main() {
d := time.Now().Add(50 * time.Millisecond)
ctx, cancel := context.WithDeadline(context.Background(), d)
//尽管ctx会过期,但在任何情况下调用它的cancel函数都是需要的
//如果不这样做,可能使上下文及其父类存活时间超过必要时间
defer cancel()
select {
case <-ctx.Done():
fmt.Println(ctx.Err())
case <-time.After(1 * time.Second):
fmt.Println("timeout...")
}
}
上面代码中,定义了一个50毫秒之后过期的deadline,然后我们调用context.WithDeadline(context.Background(), d)得到一个上下文(ctx)和取消函数(cancel),然后使用一个select让主程序陷入等待:等待1秒后打印timeout或者等待ctx过期后退出。因为ctx 50毫秒后过期,所以ctx.Done()会先接收到值,上面代码会打印ctx.Err()取消的原因。
5.3 WithTimeout
函数签名:
func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc)
WithTimeout返回WithDeadline(parent, time.Now().Add(timeout))。
取消上下文将释放与其相关的资源,因此代码应该在此上下文中运行的操作完成后立即调用cancel,通常用于数据库或者网络连接的超时控制。cancel函数是释放上下文的资源。
示例:
package main
import (
"context"
"fmt"
"sync"
"time"
)
var wg sync.WaitGroup
func worker(ctx context.Context) {
LOOP:
for {
fmt.Println("connect db...")
time.Sleep(10 * time.Millisecond) //模拟连接数据库
select {
case <-ctx.Done():
break LOOP
default:
}
}
fmt.Println("woker done")
wg.Done()
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
wg.Add(1)
go worker(ctx)
time.Sleep(5 * time.Second)
cancel() //释放上下文资源
wg.Wait()
fmt.Println("over")
}
5.4 WithValue
WithValue函数能够将请求作用域的数据与Context对象建立关系。声明如下:
func WithValue(parent Context, key, val interface{}) Context
WithValue返回父节点的副本,其中与key关联的值为val。
仅对API和进程间传递请求域的数据使用上下文值,而不是使用它来传递可选参数给函数。
所提供的键必须是可比较的,并且不应该是string类型或任何其它内置类型,以免使用上下文在包之间发生冲突。WithValue的用户应该为键定义自己的类型。为了避免在分配给interface{}时进行分配,上下文键通常具有具体类型struct{}。或者,导出的上下文关键变量的静态类型应该是指针或接口。
package main
import (
"context"
"fmt"
"sync"
"time"
)
type TradeCode string
var wg sync.WaitGroup
func worker(ctx context.Context) {
//在goroutine中获得上下文键值对
key := TradeCode("trade code")
val, ok := ctx.Value(key).(string)
if !ok {
fmt.Println("ctx invalid trace code")
}
LOOP:
for {
fmt.Printf("worker trade code : %v\n", val)
time.Sleep(time.Millisecond * 5) //假设正常连接数据库需要10毫秒
select {
case <-ctx.Done(): //50毫秒后自动调用
break LOOP
default:
}
}
fmt.Println("worker done")
wg.Done()
}
func main() {
//设置一个50毫秒超时的ctx
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
//在上下文中设置键值对
ctx = context.WithValue(ctx, TradeCode("trade code"), "123123")
wg.Add(1)
go worker(ctx)
time.Sleep(5 * time.Second)
cancel()
wg.Wait()
fmt.Println("main over")
}
六. 使用Context的注意事项
- 推荐以参数的方式显示传递Context
- 以Context作为参数的函数方法,应该把Context作为第一个参数
- 给一个函数方法传递Context的时候,不要传递nil,如果不知道传递什么,就使用Context.TODO()
- Context的Value相关方法应该传递请求域的必要数据,不应该用于传递可选参数
- Context是线程安全的,可以放心的在多个goroutine中传递
七. 客户端超时取消示例
调用服务器API时在客户端实现超时控制。
- server端
package main
import (
"fmt"
"math/rand"
"net/http"
"time"
)
func indexHander(w http.ResponseWriter, r *http.Request) {
i := rand.Intn(2)
if i == 0 {
time.Sleep(1 * time.Second)
fmt.Fprintf(w, "slow resp %v", i)
return
}
fmt.Fprintf(w, "quick resp %v", i)
}
func main() {
http.HandleFunc("/", indexHander)
err := http.ListenAndServe(":9090", nil)
if err != nil {
panic("listen fail")
}
}
- client端
package main
import (
"context"
"fmt"
"io/ioutil"
"net/http"
"sync"
"time"
)
type respData struct {
resp *http.Response
err error
}
func doCall(ctx context.Context) {
//请求频繁,设置长连接
//请求不频繁,设置短连接
tsp := &http.Transport{
DisableKeepAlives: true,
}
//新建客户端
client := &http.Client{
Transport: tsp,
}
//设置新请求
req, err := http.NewRequest("Get", "http://127.0.0.1:9090", nil)
if err != nil {
fmt.Printf("new request failed, err : %v\n", err)
return
}
//使用带超时的ctx创建新的client request
req = req.WithContext(ctx)
respChan := make(chan *respData, 1)
var wg sync.WaitGroup
wg.Add(1)
defer wg.Wait()
//请求服务器
go func() {
resp, err := client.Do(req)
fmt.Printf("resp : %v err : %v\n", resp, err)
respD := &respData{
resp,
err,
}
respChan <- respD
wg.Done()
}()
select {
case <-ctx.Done():
fmt.Println("call api timeout")
case res := <-respChan:
fmt.Println("call api sucess")
if res.err != nil {
fmt.Printf("call api fail, err : %v\n", res.err)
return
}
defer res.resp.Body.Close()
data, _ := ioutil.ReadAll(res.resp.Body)
fmt.Printf("resp : %v\n", string(data))
}
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel() //调用cancel释放上下文资源
doCall(ctx)
}