面试题答案
一键面试系统架构设计思路
- 缓存数据结构:使用
map
来存储缓存数据,由于要支持并发安全,需要使用sync.RWMutex
来保护map
的读写操作。map
的键为字符串类型,值为空接口类型interface{}
,以实现泛型存储。 - 并发控制:利用
sync.RWMutex
实现读写锁,读操作使用读锁提高并发性能,写操作使用写锁保证数据一致性。 - 过期机制:可以引入一个
time.Time
类型的字段记录每个缓存项的过期时间,在读取和写入时检查过期情况并进行相应处理。
关键代码示例
package main
import (
"fmt"
"sync"
"time"
)
type CacheItem struct {
Value interface{}
ExpiresAt time.Time
}
type Cache struct {
data map[string]CacheItem
mu sync.RWMutex
}
func NewCache() *Cache {
return &Cache{
data: make(map[string]CacheItem),
}
}
// Set 设置缓存项
func (c *Cache) Set(key string, value interface{}, duration time.Duration) {
c.mu.Lock()
defer c.mu.Unlock()
expiresAt := time.Now().Add(duration)
c.data[key] = CacheItem{Value: value, ExpiresAt: expiresAt}
}
// Get 获取缓存项
func (c *Cache) Get(key string) (interface{}, bool) {
c.mu.RLock()
item, exists := c.data[key]
c.mu.RUnlock()
if exists && time.Now().Before(item.ExpiresAt) {
return item.Value, true
}
return nil, false
}
// Delete 删除缓存项
func (c *Cache) Delete(key string) {
c.mu.Lock()
defer c.mu.Unlock()
delete(c.data, key)
}
你可以使用以下方式测试上述代码:
func main() {
cache := NewCache()
cache.Set("test", "value", 5*time.Second)
value, exists := cache.Get("test")
if exists {
fmt.Printf("Value: %v\n", value)
} else {
fmt.Println("Key not found or expired")
}
time.Sleep(6 * time.Second)
value, exists = cache.Get("test")
if exists {
fmt.Printf("Value: %v\n", value)
} else {
fmt.Println("Key not found or expired")
}
}