当前位置: > > > > 在 Go 中使用 context.WithTimeout() 时的最佳实践是什么?
在 Go 中使用 context.WithTimeout() 时的最佳实践是什么?
来源:stackoverflow
2024-05-01 08:15:32
0浏览
收藏
Golang小白一枚,正在不断学习积累知识,现将学习到的知识记录一下,也是将我的所得分享给大家!而今天这篇文章《在 Go 中使用 context.WithTimeout() 时的最佳实践是什么?》带大家来了解一下##content_title##,希望对大家的知识积累有所帮助,从而弥补自己的不足,助力实战开发!
问题内容
我想使用 context.withtimeout() 来处理我发出外部请求的用例,如果请求的响应太长,则会返回错误。
我已经实现了伪代码,如下面附加的演示链接: 2解决方案:
- 预计不会出现 main ->
- 预计为 main_1 ->
package main
import (
"context"
"fmt"
"time"
)
// I just dummy sleep in this func to produce use case this func
// need 10s to process and handle logic.
// And this assume will be out of timeOut expect (5s)
func makeHTTPRequest(ctx context.Context) (string, error) {
time.Sleep(time.Duration(10) * time.Second)
return "abc", nil
}
// In main Func, I will set timeout is 5 second.
func main() {
var strCh = make(chan string, 1)
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(5)*time.Second)
defer cancel()
fmt.Print("Begin make request\n")
abc, err := makeHTTPRequest(ctx)
if err != nil {
fmt.Print("Return error\n")
return
}
select {
case <-ctx.Done():
fmt.Printf("Return ctx error: %s\n", ctx.Err())
return
case strCh <- abc:
fmt.Print("Return response\n")
return
}
}
func main_1() {
var strCh = make(chan string, 1)
var errCh = make(chan error, 1)
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(5)*time.Second)
defer cancel()
go func() {
fmt.Print("Begin make request\n")
abc, err := makeHTTPRequest(ctx)
if err != nil {
fmt.Print("Return error\n")
errCh <- err
return
}
strCh <- abc
}()
select {
case err := <-errCh:
fmt.Printf("Return error: %s\n", err.Error())
return
case <-ctx.Done():
fmt.Printf("Return ctx error: %s\n", ctx.Err())
return
case str := <-strCh:
fmt.Printf("Return response: %s\n", str)
return
}
}
但是,如果使用 main() 函数,则它无法按预期工作。 但是如果第二个 main_1() 使用 goroutine 实现,那么新的 context.withtimeout() 可能会按预期工作。
你能帮我解答一下这个问题吗?
https://play.golang.org/p/kzdlm_tvljy
解决方案
最好在 makehttprequest() 函数中处理上下文,这样您就可以将其用作 main() 中的同步函数。
func makeHTTPRequest(ctx context.Context) (string, error) {
ch := make(chan string)
go func() {
time.Sleep(10 * time.Second)
select {
case ch <- "abc":
default:
// When context deadline exceeded, there is no receiver
// This case will prevent goroutine blocking forever
return
}
}()
select {
case <-ctx.Done():
return "", ctx.Err()
case result := <-ch:
return result, nil
}
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
fmt.Printf("[%v] Begin make request \n", time.Now())
abc, err := makeHTTPRequest(ctx)
if err != nil {
fmt.Printf("[%v] Return error: %v \n", time.Now(), err)
return
}
fmt.Printf("[%v] %s", time.Now(), abc)
}
如果我没猜错的话。有两个问题。
- 您想知道为什么 main() 函数不起作用?
- 最佳做法是什么?
第一季度
main() 在 makehttprequest 处被阻止,在此期间,上下文超时。因此,没有按预期工作。
第二季度
这个可以回答你。在 main_1() 中,您的代码已经是最佳实践。
好了,本文到此结束,带大家了解了《在 Go 中使用 context.WithTimeout() 时的最佳实践是什么?》,希望本文对你有所帮助!关注米云公众号,给大家分享更多Golang知识!
