在CentOS上配置Golang緩存可以通過多種方式實現,以下是一些常見的方法:
安裝Redis服務器
sudo yum install epel-release
sudo yum install redis
sudo systemctl start redis
sudo systemctl enable redis
安裝Golang Redis客戶端
go get github.com/go-redis/redis/v8
編寫Golang代碼使用Redis作為緩存
package main
import (
"context"
"fmt"
"github.com/go-redis/redis/v8"
"time"
)
var ctx = context.Background()
func main() {
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password set
DB: 0, // use default DB
})
// Set a key-value pair with an expiration time
err := rdb.Set(ctx, "mykey", "myvalue", 10*time.Second).Err()
if err != nil {
panic(err)
}
// Get the value from Redis
val, err := rdb.Get(ctx, "mykey").Result()
if err == redis.Nil {
fmt.Println("Key does not exist")
} else if err != nil {
panic(err)
} else {
fmt.Println("Key:", val)
}
}
package main
import (
"fmt"
"io/ioutil"
"os"
"time"
)
func main() {
cacheFile := "cache.txt"
// Check if the cache file exists
if _, err := os.Stat(cacheFile); os.IsNotExist(err) {
// Cache file does not exist, create it
data := []byte("myvalue")
ioutil.WriteFile(cacheFile, data, 0644)
}
// Read the cache file
data, err := ioutil.ReadFile(cacheFile)
if err != nil {
panic(err)
}
fmt.Println("Cached value:", string(data))
// Simulate cache expiration
time.Sleep(10 * time.Second)
// Check if the cache file still exists
if _, err := os.Stat(cacheFile); os.IsNotExist(err) {
fmt.Println("Cache expired")
} else {
fmt.Println("Cache still valid")
}
}
安裝groupcache
go get github.com/golang/groupcache
編寫Golang代碼使用groupcache作為緩存
package main
import (
"fmt"
"net/http"
"sync"
"time"
"github.com/golang/groupcache"
)
var cache = groupcache.NewGroup("example", 64<<20, groupcache.GetterFunc(
func(ctx context.Context, key string, dest groupcache.Sink) error {
// Simulate fetching data from a database or other source
data := "myvalue"
dest.SetBytes([]byte(data))
return nil
},
))
func handler(w http.ResponseWriter, r *http.Request) {
key := r.URL.Query().Get("key")
var buf [1 << 20]byte
n, err := cache.Get(ctx, key, groupcache.AllocatingByteSliceSink(&buf))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Write(buf[:n])
}
func main() {
http.HandleFunc("/", handler)
fmt.Println("Starting server at port 8080")
if err := http.ListenAndServe(":8080", nil); err != nil {
panic(err)
}
}
以上方法展示了在CentOS上配置Golang緩存的幾種常見方式,包括使用Redis、文件緩存和第三方緩存庫(如groupcache)。選擇哪種方法取決于你的具體需求和應用場景。