關于Redis的討論,其實在現在的后臺開發中已經是個老生常談的問題,基本上也是后端開發面試的基本考察點。其中 Redis的背景介紹和細節說明在這里就不贅述。不管怎么介紹,核心在于Redis是一個基于內存的key-value的多數據結構存儲,并可以提供持久化服務。基于內存的特性決定了Redis天然適合高并發的數據讀寫緩存優化,同時也帶來了內存開銷過大的問題。所以在一些特定情景下,Redis是一把無往不利的大殺器,值得深入學習。
package main
import (
"time"
"fmt"
"github.com/go-redis/redis"
)
var Client *redis.Client
func init() {
Client = redis.NewClient(redis.Options{
Addr: "127.0.0.1:6379",
PoolSize: 1000,
ReadTimeout: time.Millisecond * time.Duration(100),
WriteTimeout: time.Millisecond * time.Duration(100),
IdleTimeout: time.Second * time.Duration(60),
})
_, err := Client.Ping().Result()
if err != nil {
panic("init redis error")
} else {
fmt.Println("init redis ok")
}
}
func get(key string) (string, bool) {
r, err := Client.Get(key).Result()
if err != nil {
return "", false
}
return r, true
}
func set(key string, val string, expTime int32) {
Client.Set(key, val, time.Duration(expTime) * time.Second)
}
func main() {
set("name", "x", 100)
s, b := get("name")
fmt.Println(s, b)
}