go语言context.Context应用

89 阅读2分钟

需求:

发生超时后, 不继续执行后续逻辑, 实现不浪费资源的目的 场景: 比如我们有一个请求, 会执行很多查询数据库, redis等操作, 这种请求往往很消耗系统资源, 数据库、redis、系统CPU、内存等都是较大的负担, 因此, 我们需要一个能在发生超时后, 不继续执行后续逻辑, 从而避免资源的浪费, 也能增加系统的稳定性.

1. 常规业务场景

  • 模拟业务执行逻辑耗时
func Logic(ctx context.Context, name string, duration time.Duration) {
   log.Println("task: ", name)
   time.Sleep(duration)
}
  • 模拟具体业务链
func Task1(ctx context.Context) {
   Logic(ctx, "task1", time.Second*3)
   Logic(ctx, "task2", time.Second*3)
   Logic(ctx, "task3", time.Second*3)
   Logic(ctx, "task4", time.Second*3)
   Logic(ctx, "task5", time.Second*3)
   Logic(ctx, "task6", time.Second*3)
   Logic(ctx, "task7", time.Second*3)
}
  • 模拟业务具体执行
func main() {
   go Task1(ctx)

   for {

   }
}
  • 正常执行结果
2023/02/28 17:52:53 task:  task1
2023/02/28 17:52:56 task:  task2
2023/02/28 17:52:59 task:  task3
2023/02/28 17:53:02 task:  task4
2023/02/28 17:53:05 task:  task5
2023/02/28 17:53:08 task:  task6
2023/02/28 17:53:11 task:  task7

2. 加入超时context

func main() {
   ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
   defer cancel()

   go Task1(ctx)

   select {
   case <-ctx.Done():
      log.Println("canceled end")
   }

   for {

   }
}
  • 常规超时执行结果
2023/02/28 17:57:37 task:  task1
2023/02/28 17:57:40 task:  task2
2023/02/28 17:57:42 canceled end
2023/02/28 17:57:43 task:  task3
2023/02/28 17:57:46 task:  task4
2023/02/28 17:57:49 task:  task5
2023/02/28 17:57:52 task:  task6
2023/02/28 17:57:55 task:  task7

从执行数据来看, 虽然监听到了超时信号, 但是此时子协程已经在运行队列, 无法从外部进行中断, 所以也不能停止执行, 该消耗的资源还是会被消耗

3. 子逻辑增加超时检测

  • 编写超时检测函数
func Timeout(ctx context.Context) (status bool) {
   select {
   case <-ctx.Done():
      log.Println("canceled...")
      return true
   default:
      return
   }
}
  • 子业务加入超时判断逻辑
func Logic(ctx context.Context, name string, duration time.Duration) {
   if Timeout(ctx) {
      return
   }
   log.Println("task: ", name)
   time.Sleep(duration)
}
  • 执行结果
2023/02/28 18:04:58 task:  task1
2023/02/28 18:05:01 task:  task2
2023/02/28 18:05:03 canceled end
2023/02/28 18:05:04 canceled...
2023/02/28 18:05:04 canceled...
2023/02/28 18:05:04 canceled...
2023/02/28 18:05:04 canceled...
2023/02/28 18:05:04 canceled...

可以发现, 当超时信号发生时, 后续逻辑虽然被触发, 但是并没有进入耗时环节, 这样就避免了耗时、耗资源的事件在超时后还无意义执行的情况.

4.完整程序

package main

import (
   "context"
   "log"
   "time"
)

// Timeout 耗时检测
func Timeout(ctx context.Context) (status bool) {
   select {
   case <-ctx.Done():
      log.Println("canceled...")
      return true
   default:
      return
   }
}

// Logic 模拟子业务逻辑
func Logic(ctx context.Context, name string, duration time.Duration) {
   if Timeout(ctx) {
      return
   }
   log.Println("task: ", name)
   time.Sleep(duration)
}

// Task1 模拟具体业务逻辑
func Task1(ctx context.Context) {
   Logic(ctx, "task1", time.Second*3)
   Logic(ctx, "task2", time.Second*3)
   Logic(ctx, "task3", time.Second*3)
   Logic(ctx, "task4", time.Second*3)
   Logic(ctx, "task5", time.Second*3)
   Logic(ctx, "task6", time.Second*3)
   Logic(ctx, "task7", time.Second*3)
}

func main() {
   ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
   defer cancel()
   //ctx := context.Background()
   go Task1(ctx)

   select {
   case <-ctx.Done():
      log.Println("canceled end")
   }

   for {
        // 死循环, 不允许主协程退出
   }
}