温馨提示×

go怎么实现本地缓存

go
小亿
127
2023-11-07 13:51:41
栏目: 编程语言
GO开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Go语言中,可以使用`sync.Map`或者`map`来实现本地缓存。
1. 使用`sync.Map`实现本地缓存:

package main
import (
"sync"
"time"
)
type Cache struct {
data sync.Map
}
func (c *Cache) Get(key string) (interface{}, bool) {
value, ok := c.data.Load(key)
if ok {
return value, true
}
return nilfalse
}
func (c *Cache) Set(key string, value interface{}) {
c.data.Store(key, value)
}
func (c *Cache) Delete(key string) {
c.data.Delete(key)
}
func main() {
cache := &Cache{}
cache.Set("key1""value1")
cache.Set("key2""value2")
value, ok := cache.Get("key1")
if ok {
println(value.(string)) // 输出:value1
}
cache.Delete("key2")
value, ok = cache.Get("key2")
if !ok {
println("key2 not found"// 输出:key2 not found
}
}

2. 使用`map`实现本地缓存:

package main
import "time"
type Cache struct {
data   map[string]interface{}
expiry map[string]time.Time
}
func (c *Cache) Get(key string) (interface{}, bool) {
value, ok := c.data[key]
if ok {
expiryTime := c.expiry[key]
if expiryTime.After(time.Now()) {
return value, trueelse {
delete(c.data, key)
delete(c.expiry, key)
return nilfalse
}
}
return nilfalse
}
func (c *Cache) Set(key string, value interface{}, expiry time.Duration) {
c.data[key] = value
c.expiry[key] = time.Now().Add(expiry)
}
func (c *Cache) Delete(key string) {
delete(c.data, key)
delete(c.expiry, key)
}
func main() {
cache := &Cache{
data:   make(map[string]interface{}),
expiry: make(map[string]time.Time),
}
cache.Set("key1""value1", time.Second*10)
cache.Set("key2""value2", time.Second*20)
value, ok := cache.Get("key1")
if ok {
println(value.(string)) // 输出:value1
}
time.Sleep(time.Second * 15)
value, ok = cache.Get("key1")
if !ok {
println("key1 not found"// 输出:key1 not found
}
}

以上是两种常见的在Go语言中实现本地缓存的方法,选择使用哪种取决于你对并发安全性和性能的需求。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:hashmap怎么实现本地缓存

0