在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中使用不同的緩存技術。你可以根據自己的需求選擇合適的緩存策略和庫。