• ctx控制超时的使用


    cancel
    package main
    
    import (
        "context"
        "fmt"
        "time"
    )
    
    func gen(ctx context.Context) <-chan int {
        dst := make(chan int)
        n := 1
        go func() {
            for {
                select {
                case <-ctx.Done():
                    fmt.Println("i exited")
                    return // returning not to leak the goroutine
                case dst <- n:
                    n++
                }
            }
        }()
        return dst
    }
    
    func test() {
        // gen generates integers in a separate goroutine and
        // sends them to the returned channel.
        // The callers of gen need to cancel the context once
        // they are done consuming generated integers not to leak
        // the internal goroutine started by gen.
        ctx, cancel := context.WithCancel(context.Background())
        defer cancel() // cancel when we are finished consuming integers
        intChan := gen(ctx)
        for n := range intChan {
            fmt.Println(n)
            if n == 5 {
                break
            }
        }
    }
    func main() {
        test()
        time.Sleep(time.Hour)
    }
    
    deadline
    package main
    
    import (
        "context"
        "fmt"
        "time"
    )
    
    func main() {
        d := time.Now().Add(1000 * time.Millisecond)
        ctx, cancel := context.WithDeadline(context.Background(), d)
    
        // Even though ctx will be expired, it is good practice to call its
        // cancelation function in any case. Failure to do so may keep the
        // context and its parent alive longer than necessary.
        defer cancel()
    
        select {
        case <-time.After(1 * time.Second):
            fmt.Println("overslept")
        case <-ctx.Done():
            fmt.Println(ctx.Err())
        }
    
    }
    
    timeout
    package main
    
    import (
        "context"
        "fmt"
        "io/ioutil"
        "net/http"
        "time"
    )
    type Result struct {
        r   *http.Response
        err error
    }
    func process() {
        ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
        defer cancel()
        tr := &http.Transport{}
        client := &http.Client{Transport: tr}
        c := make(chan Result, 1)
        req, err := http.NewRequest("GET", "http://www.baidu.com", nil)
        if err != nil {
            fmt.Println("http request failed, err:", err)
            return
        }
        go func() {
            resp, err := client.Do(req)
            pack := Result{r: resp, err: err}
            c <- pack
        }()
        select {
        case <-ctx.Done():
            tr.CancelRequest(req)
            res := <-c
            fmt.Println("Timeout! err:", res.err)
        case res := <-c:
            defer res.r.Body.Close()
            out, _ := ioutil.ReadAll(res.r.Body)
            fmt.Printf("Server Response: %s", out)
        }
        return
    }
    func main() {
        process()
    }
    

    value

    package main
    
    import (
        "context"
        "fmt"
    )
    
    func process(ctx context.Context) {
        ret,ok := ctx.Value("trace_id").(int)
        if !ok {
            ret = 21342423
        }
    
        fmt.Printf("ret:%d
    ", ret)
    
        s , _ := ctx.Value("session").(string)
        fmt.Printf("session:%s
    ", s)
    }
    
    func main() {
        ctx := context.WithValue(context.Background(), "trace_id", 13483434)
        ctx = context.WithValue(ctx, "session", "sdlkfjkaslfsalfsafjalskfj")
        process(ctx)
    }
    




  • 相关阅读:
    ubuntu18.04下eclipse修改maven源为阿里源
    Java中使用队列Queue
    Redis学习笔记——Redis的基本操作
    ubuntu安装redis
    Spring Boot使用监听器Listener
    Spring Boot中在程序中获得application.properties中的值
    Spring Boot使用过滤器Filter
    基于GTID的主从架构异常处理流程
    goroutine与调度器
    使用synergyc共享键鼠
  • 原文地址:https://www.cnblogs.com/hualou/p/12069669.html
Copyright © 2020-2023  润新知