Go context 全局变量参数

摘要1:

golang 上下文context用法详解 - 孙龙-程序员 - 博客园背景 在go服务器中,对于每个请求的request都是在单独的goroutine中进行的,处理一个request也可能设计多个goroutine之间的交互, 使用context可以使开发者方便的在这些https://www.cnblogs.com/sunlong88/p/11272559.html摘要2:

golang-context详解 - 知乎个人公众号『码农札记』,欢迎关注,查看更多精彩文章。 简介context.Context 是golang中独特的涉及,可以用来用来设置截止日期、同步信号,传递请求相关值的结构体。 与 Goroutine 有比较密切的关系。 在web程序中…https://zhuanlan.zhihu.com/p/266318909

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)
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值