面试题答案
一键面试package main
import (
"context"
"fmt"
"time"
)
func downstreamService(ctx context.Context) {
select {
case <-time.After(5 * time.Second): // 模拟下游服务调用可能花费较长时间
fmt.Println("下游服务处理完成")
case <-ctx.Done():
fmt.Println("下游服务超时,被取消:", ctx.Err())
}
}
func main() {
// 创建一个带有超时的Context
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
// 调用下游服务
downstreamService(ctx)
}
在上述代码中:
context.WithTimeout(context.Background(), 3*time.Second)
创建了一个带有3秒超时的Context
以及对应的取消函数cancel
。- 在
downstreamService
函数中,通过select
语句监听ctx.Done()
通道,如果在5秒的模拟处理时间内收到ctx.Done()
信号,说明超时,会打印超时信息并结束处理;如果正常完成模拟处理(5秒内未超时),则打印处理完成信息。 - 在
main
函数中,调用downstreamService(ctx)
时传递带有超时设置的Context
,这样下游服务就可以根据Context
的设置来判断是否超时。