在Linux下使用Golang进行缓存技术,你可以选择多种缓存策略和库。以下是一些常见的缓存技术和如何在Golang中实现它们的示例:
package main
import (
"fmt"
"sync"
)
type Cache struct {
sync.Mutex
data map[string]interface{}
}
func NewCache() *Cache {
return &Cache{
data: make(map[string]interface{}),
}
}
func (c *Cache) Get(key string) (interface{}, bool) {
c.Lock()
defer c.Unlock()
value, found := c.data[key]
return value, found
}
func (c *Cache) Set(key string, value interface{}) {
c.Lock()
defer c.Unlock()
c.data[key] = value
}
func main() {
cache := NewCache()
cache.Set("key", "value")
value, found := cache.Get("key")
if found {
fmt.Println("找到缓存:", value)
} else {
fmt.Println("未找到缓存")
}
}
go-cache和ristretto。使用go-cache:
package main
import (
"fmt"
"time"
"github.com/patrickmn/go-cache"
)
func main() {
c := cache.New(5*time.Minute, 10*time.Minute)
c.Set("key", "value", cache.DefaultExpiration)
value, found := c.Get("key")
if found {
fmt.Println("找到缓存:", value)
} else {
fmt.Println("未找到缓存")
}
}
使用ristretto:
package main
import (
"fmt"
"github.com/dgraph-io/ristretto"
)
func main() {
cache, err := ristretto.NewCache(&ristretto.Options{
NumCounters: 1e7, // number of keys to track frequency of (10M).
MaxCost: 1 << 30, // maximum cost of cache (1GB).
BufferItems: 64, // number of keys per Get buffer.
})
if err != nil {
panic(err)
}
err = cache.Set("key", "value", 1)
if err != nil {
panic(err)
}
value, found := cache.Get("key")
if found {
fmt.Println("找到缓存:", value)
} else {
fmt.Println("未找到缓存")
}
}
使用Redis:
package main
import (
"fmt"
"github.com/go-redis/redis/v8"
)
func main() {
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password set
DB: 0, // use default DB
})
err := rdb.Set(ctx, "key", "value", 0).Err()
if err != nil {
panic(err)
}
value, err := rdb.Get(ctx, "key").Result()
if err == redis.Nil {
fmt.Println("未找到缓存")
} else if err != nil {
panic(err)
} else {
fmt.Println("找到缓存:", value)
}
}
这些示例展示了如何在Golang中使用不同的缓存技术。你可以根据自己的需求选择合适的缓存策略和库。