摘要1:
WithValue示例:
设置上下文变量
pacake main
import (
"context"
"fmt"
)
func process(ctx context.Context) {
ret, ok := ctx.Value("trace_id").(int) // 类型断言
if !ok {
ret = 16464
}
fmt.Printf("ret:%d\n", ret)
ret2, _ := ctx.Value("session").(string) // 类型断言
fmt.Printf("session:%d\n", ret2)
}
func main() {
ctx := contxt.WithValue(context.Background(), "trace_id", 64448)
// 继承ctx
ctx = context.WithValue(ctx, "session", sdfsddsfdsfe)
process(ctx)
}
WithTimeout示例:
设置函数超时时间
ctx, cancel := context.WithTimeout(context.Background(), time.Second) // 超时时间为1秒
_, err = cli.put(ctx, "/logagent/conf", "sample_value") // 操作etcd
cancel() // 取消ctx
if err != nil {
fmt.Println("put failed , err: ", err)
return
}
WithCancel示例:
退出程序
示例1:
packge main
import (
"fmt"
"context"
)
func process() {
gen := func(ctx context.Context) <-chan int {
dst := make(chan int)
n := 1
go func() {
for {
select {
case <-ctx.Done():
fmt.Println("I exited")
return
case dst <- n:
n++
}
}
}()
return dst
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel() // 程序退出之前执行
for n := gen(ctx) {
fmt.Println(n)
if n == 5 {
break // 退出for循环
}
}
}
func main() {
process()
}
示例2:
package main
import (
"fmt"
)
func ReqTask(ctx context.Context, name string) {
for {
select {
case <-ctx.Done():
fmt.Println("game over", name)
return
default:
fmt.Println("req task is runing", name)
time.Sleep(time.Second)
}
}
}
func main() {
ctx, cancel := context.WithCancel(context.Background())
go ReqTask(ctx, "aaa")
go ReqTask(ctx, "bbb")
go ReqTask(ctx, "ccc")
time.Sleep(time.Second*3)
cancel() // 通知退出
time.Sleep(time.Second*3)
}