在 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

点赞
收藏

评论区

加载中...

相关推荐

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

mysql设置时区

mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0

Go 用 interface 模拟多态

多态是C这种语言中的概念,是指对不同的子类对象运行自己定义的方法。在Go语言中没有类的概念,但仍然可以使用structinterface来模拟实现类的功能。下面这个例子演示如何使用Go来模拟C中的多态行为。packagemainimport"fmt"//首先定义了一

Go语言 之结构体比较与赋值

packagemainimport("fmt")typeStudentstruct{idintnamestring}funcmain(){//比较s1:S

Go 语言 bytes.FieldsFunc 函数的使用

packagemainimport("bytes""fmt""reflect""strings")funcmain(){sentence:byte("TheGolanguagehasbuiltinfac