可以参考以下代码示例:
package main
import (
"fmt"
"time"
)
// Cache 定义一个简单的缓存结构
type Cache struct {
// map存储键值对
items map[string]Item
// 默认过期时间
defaultExpiration time.Duration
}
// Item 定义一个项结构,包含过期时间
type Item struct {
value string
expires time.Time
}
// Set 方法用于设置缓存项,指定键、值以及过期时间
func (c *Cache) Set(key, value string, expiration time.Duration) {
// 计算过期时间
item := Item{
value: value,
expires: time.Now().Add(expiration),
}
// 存储到map中
c.items [key] = item
}
func main() {
cache := &Cache{
items: make(map[string]Item),
defaultExpiration: 20 * time.Second, // 默认过期时间为30秒
}
// 设置缓存项
cache.Set("key1", "value1", 10*time.Second)
cache.Set("key2", "value2", 20*time.Second)
// 获取缓存项
value, exists := cache.Get("key1")
if exists {
fmt.Println(value)
} else {
fmt.Println("Key does not exist.")
}
}