在 CentOS 系统上使用 Golang 设置缓存,你可以使用第三方库,例如 go-cache 或者使用 Redis 作为缓存存储。以下是两种方法的简要说明:
方法一:使用 go-cache
go get github.com/patrickmn/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)
// 获取缓存项
if x, found := c.Get("key"); found {
fmt.Println("key:", x)
} else {
fmt.Println("key not found")
}
}
方法二:使用 Redis
sudo yum install epel-release
sudo yum install redis
sudo systemctl start redis
sudo systemctl enable redis
go get github.com/go-redis/redis/v8
package main
import (
"context"
"fmt"
"github.com/go-redis/redis/v8"
)
func main() {
ctx := context.Background()
// 创建一个 Redis 客户端实例
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // 如果没有设置密码,则留空
DB: 0, // 使用默认数据库
})
// 设置缓存项
err := rdb.Set(ctx, "key", "value", 5*time.Minute).Err()
if err != nil {
panic(err)
}
// 获取缓存项
val, err := rdb.Get(ctx, "key").Result()
if err == redis.Nil {
fmt.Println("key not found")
} else if err != nil {
panic(err)
} else {
fmt.Println("key:", val)
}
}
这两种方法都可以在 CentOS 系统上使用 Golang 设置缓存。你可以根据自己的需求选择合适的方法。