面试题答案
一键面试- 基本步骤概述:
- 创建context:可以使用
context.Background()
创建一个空的上下文作为根上下文,也可以基于现有的上下文使用context.WithCancel
、context.WithDeadline
、context.WithTimeout
等函数创建具有特定取消或截止功能的上下文。 - 传递context:将创建好的上下文传递给涉及缓存操作的函数,包括缓存读取、写入等函数。
- 检查context:在缓存操作函数内部,定期检查上下文的状态,例如是否被取消或是否已达到截止时间。如果上下文状态表明操作应该停止,函数应尽快结束并返回适当的错误。
- 创建context:可以使用
- 在缓存读取函数中引入context示例:
package main
import (
"context"
"fmt"
"time"
)
// 模拟缓存数据结构
type Cache struct {
data map[string]string
}
// 缓存读取函数,引入context
func (c *Cache) Get(ctx context.Context, key string) (string, error) {
// 模拟一些可能的延迟操作
select {
case <-ctx.Done():
return "", ctx.Err()
case <-time.After(1 * time.Second):
if value, ok := c.data[key]; ok {
return value, nil
}
return "", fmt.Errorf("key not found")
}
}
func main() {
cache := Cache{
data: map[string]string{
"key1": "value1",
}
}
// 创建带超时的上下文
ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
defer cancel()
value, err := cache.Get(ctx, "key1")
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println("Value:", value)
}
}
在上述示例中:
- 首先创建了一个简单的
Cache
结构体来模拟缓存。 Get
方法中,使用select
语句监听ctx.Done()
通道。如果上下文被取消(例如超时),ctx.Done()
通道会收到值,函数将返回错误。如果在超时时间内获取到缓存值,则正常返回。- 在
main
函数中,创建了一个带超时的上下文ctx
,并将其传递给cache.Get
函数,以此来管理缓存读取操作的上下文。