Go 协程超时控制的实现

2022-07-22,

目录

go 协程超时控制

  • select 阻塞方式
  • context 方式

先说个场景:

假设业务中 a 服务需要调用 服务b,要求设置 5s 超时,那么如何优雅实现?

select 超时控制

考虑是否可以用 select + time.after 方式进行实现

这里主要利用的是通道在携程之间通信的特点,当程序调用成功后,会向通道中发送信号。没调用成功前,通道会阻塞。

select {
 case res := <-c2:
  fmt.println(res)
 case <-time.after(time.second * 3):
  fmt.println("timeout 2")
 }

当 c2 通道中有数据时,并且超时时间没有达到 3s,走 case res := <-c2 这个业务逻辑,当超时时间达到 3s , 走的 case <-time.after(time.second * 3) 这个业务逻辑, 这样就可以实现超时 3s 的控制。

res:= <-c2 是因为channel 可以实现阻塞,那么 time.after 为啥可以阻塞呢?

看 after 源码。sleep.go 可以看到其实也是 channel

func after(d duration) <-chan time {
 return newtimer(d).c
}

完整代码示例:

package timeout

import (
 "fmt"
 "testing"
 "time"
)

func testselecttimeout(t *testing.t) {
 // 在这个例子中, 假设我们执行了一个外部调用, 2秒之后将结果写入c1
 c1 := make(chan string, 1)
 go func() {
  time.sleep(time.second * 2)
  c1 <- "result 1"
 }()
 // 这里使用select来实现超时, `res := <-c1`等待通道结果,
 // `<- time.after`则在等待1秒后返回一个值, 因为select首先
 // 执行那些不再阻塞的case, 所以这里会执行超时程序, 如果
 // `res := <-c1`超过1秒没有执行的话
 select {
 case res := <-c1:
  fmt.println(res)
 case <-time.after(time.second * 1):
  fmt.println("timeout 1")
 }
 // 如果我们将超时时间设为3秒, 这个时候`res := <-c2`将在
 // 超时case之前执行, 从而能够输出写入通道c2的值
 c2 := make(chan string, 1)
 go func() {
  time.sleep(time.second * 2)
  c2 <- "result 2"
 }()
 select {
 case res := <-c2:
  fmt.println(res)
 case <-time.after(time.second * 3):
  fmt.println("timeout 2")
 }
}

运行结果:

=== run   testselecttimeout
timeout 1
result 2
--- pass: testselecttimeout (3.00s)
pass

go timer 计时器

这个是 timer 类似的计时器实现,通用也是通过通道来发送数据。

package main
import "time"
import "fmt"
func main() {
  // ticker使用和timer相似的机制, 同样是使用一个通道来发送数据。
  // 这里我们使用range函数来遍历通道数据, 这些数据每隔500毫秒被
  // 发送一次, 这样我们就可以接收到
  ticker := time.newticker(time.millisecond * 500)
  go func() {
    for t := range ticker.c {
    fmt.println("tick at", t)
    }
  }()
  // ticker和timer一样可以被停止。 一旦ticker停止后, 通道将不再
  // 接收数据, 这里我们将在1500毫秒之后停止
  time.sleep(time.millisecond * 1500)
  ticker.stop()
  fmt.println("ticker stopped")
}

go context

context 监听是否有 io 操作,开始从当前连接中读取网络请求,每当读取到一个请求则会将该cancelctx传入,用以传递取消信号,可发送取消信号,取消所有进行中的网络请求。

  go func(ctx context.context, info *info) {
   timelimit := 120
   timeoutctx, cancel := context.withtimeout(ctx, time.duration(timelimit)*time.millisecond)
   defer func() {
    cancel()
    wg.done()
   }()
   resp := dohttp(timeoutctx, info.req)
  }(ctx, info)

关键看业务代码: resp := dohttp(timeoutctx, info.req) 业务代码中包含 http 调用 newrequestwithcontext

req, err := http.newrequestwithcontext(ctx, "post", url, strings.newreader(paramstring))

上面的代码,设置了过期时间,当dohttp(timeoutctx, info.req) 处理时间超过超时时间时,会自动截止,并且打印 context deadline exceeded。

看个代码:

package main

import (
 "context"
 "fmt"
 "testing"
 "time"
)

func testtimercontext(t *testing.t) {
 now := time.now()
 later, _ := time.parseduration("10s")

 ctx, cancel := context.withdeadline(context.background(), now.add(later))
 defer cancel()
 go monitor(ctx)

 time.sleep(20 * time.second)

}

func monitor(ctx context.context) {
 select {
 case <-ctx.done():
  fmt.println(ctx.err())
 case <-time.after(20 * time.second):
  fmt.println("stop monitor")
 }
}

运行结果:

=== run   testtimercontext
context deadline exceeded
--- pass: testtimercontext (20.00s)
pass

context 接口有如下:

type context interface {
    deadline() (deadline time.time, ok bool)
    done() <-chan struct{}
    err() error
    value(key interface{}) interface{}
}
  • deadline — 返回 context.context 被取消的时间,也就是完成工作的截止日期;
  • done — 返回一个 channel,这个 channel 会在当前工作完成或者上下文被取消之后关闭,多次调用 done 方法会返回同一个 channel;
  • err — 返回 context.context 结束的原因,它只会在 done 返回的 channel 被关闭时才会返回非空的值;
    • 如果 context.context 被取消,会返回 canceled 错误;
    • 如果 context.context 超时,会返回 deadlineexceeded 错误;
  • value — 从 context.context 中获取键对应的值,对于同一个上下文来说,多次调用 value 并传入相同的 key 会返回相同的结果,该方法可以用来传递请求特定的数据;

到此这篇关于go 协程超时控制的实现的文章就介绍到这了,更多相关go 协程超时控制内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

《Go 协程超时控制的实现.doc》

下载本文的Word格式文档,以方便收藏与打印。