centos

CentOS Golang缓存如何设置

小樊
45
2025-11-05 17:13:38
栏目: 编程语言

在 CentOS 系统上使用 Golang 设置缓存,你可以使用第三方库,例如 go-cache 或者使用 Redis 作为缓存存储。以下是两种方法的简要说明:

方法一:使用 go-cache

  1. 首先,安装 go-cache 库:
go get github.com/patrickmn/go-cache
  1. 在你的 Golang 代码中,导入并使用 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

  1. 安装 Redis 服务器:
sudo yum install epel-release
sudo yum install redis
  1. 启动并设置 Redis 开机自启:
sudo systemctl start redis
sudo systemctl enable redis
  1. 安装 Redis 客户端库:
go get github.com/go-redis/redis/v8
  1. 在你的 Golang 代码中,导入并使用 Redis:
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 设置缓存。你可以根据自己的需求选择合适的方法。

0
看了该问题的人还看了