可以参考以下代码示例:

  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. )
  6. // Cache 定义一个简单的缓存结构
  7. type Cache struct {
  8. // map存储键值对
  9. items map[string]Item
  10. // 默认过期时间
  11. defaultExpiration time.Duration
  12. }
  13. // Item 定义一个项结构,包含过期时间
  14. type Item struct {
  15. value string
  16. expires time.Time
  17. }
  18. // Set 方法用于设置缓存项,指定键、值以及过期时间
  19. func (c *Cache) Set(key, value string, expiration time.Duration) {
  20. // 计算过期时间
  21. item := Item{
  22. value: value,
  23. expires: time.Now().Add(expiration),
  24. }
  25. // 存储到map中
  26. c.items [key] = item
  27. }
  28. func main() {
  29. cache := &Cache{
  30. items: make(map[string]Item),
  31. defaultExpiration: 20 * time.Second, // 默认过期时间为30秒
  32. }
  33. // 设置缓存项
  34. cache.Set("key1", "value1", 10*time.Second)
  35. cache.Set("key2", "value2", 20*time.Second)
  36. // 获取缓存项
  37. value, exists := cache.Get("key1")
  38. if exists {
  39. fmt.Println(value)
  40. } else {
  41. fmt.Println("Key does not exist.")
  42. }
  43. }