在 Go 语言中,实现缓存的多种方式

第1种,使用sync.Map 代码示例


import (
    "fmt"
    "sync"
    "time"
)

func main() {
    var cache sync.Map

    // 存储数据到缓存
    cache.Store("key1", "value1")
    cache.Store("key2", 20)

    // 读取数据
    if value, ok := cache.Load("key1"); ok {
        fmt.Println(value)
    }

    // 遍历缓存
    cache.Range(func(key, value interface{}) bool {
        fmt.Printf("Key: %v, Value: %v\n", key, value)
        return true
    })

    // 删除数据
    cache.Delete("key1")
}

第2种,使用第三方库 github.com/patrickmn/go-cache


import (
    "fmt"
    "time"

    "github.com/patrickmn/go-cache"
)

func main() {
    c := cache.New(5*time.Minute, 10*time.Minute)

    // 添加数据到缓存
    c.Set("key1", "value1", cache.DefaultExpiration)
    c.Set("key2", 20, time.Minute)

    // 获取数据
    if value, found := c.Get("key1"); found {
        fmt.Println(value)
    }

    // 遍历缓存
    for key, value := range c.Items() {
        fmt.Printf("Key: %v, Value: %v\n", key, value.Object)
    }

    // 删除数据
    c.Delete("key1")
}

第3种,自己实现简单的缓存结构


import (
    "fmt"
    "time"
)

type CacheItem struct {
    Value      interface{}
    Expiration time.Time
}

type Cache struct {
    items map[string]CacheItem
}

func (c *Cache) Set(key string, value interface{}, expiration time.Duration) {
    c.items[key] = CacheItem{
        Value:      value,
        Expiration: time.Now().Add(expiration),
    }
}

func (c *Cache) Get(key string) interface{} {
    if item, exists := c.items[key]; exists && time.Now().Before(item.Expiration) {
        return item.Value
    }
    return nil
}

func (c *Cache) Delete(key string) {
    delete(c.items, key)
}

func main() {
    c := &Cache{items: make(map[string]CacheItem)}

    c.Set("key1", "value1", time.Minute)

    if value := c.Get("key1"); value!= nil {
        fmt.Println(value)
    }
}

第4种 Redis 缓存的示例代码

 package main

import (
    "fmt"
    "github.com/go-redis/redis"
)

func main() {
    // 创建 Redis 客户端
    client := redis.NewClient(&redis.Options{
        Addr:     "localhost:6379", // Redis 服务器地址和端口
        Password: "",               // 如果有密码,在此设置
        DB:       0,                // 选择数据库
    })

    // 测试连接
    pong, err := client.Ping().Result()
    if err!= nil {
        fmt.Println("连接 Redis 失败:", err)
        return
    }
    fmt.Println("连接成功:", pong)

    // 设置键值对
    err = client.Set("key1", "value1", 0).Err()
    if err!= nil {
        fmt.Println("设置值失败:", err)
        return
    }

    // 获取值
    value, err := client.Get("key1").Result()
    if err!= nil {
        fmt.Println("获取值失败:", err)
        return
    }
    fmt.Println("获取的值:", value)

    // 关闭 Redis 客户端连接
    defer client.Close()
}

请注意,在实际应用中,您可能需要处理更多的错误情况,并根据具体的业务需求进行更复杂的操作,如批量操作、数据类型的处理等。同时,如果您的 Redis 服务器不是在本地运行,需要将 Addr 参数修改为实际的服务器地址和端口。

文章出处:在线工具800

评论

暂无评论