跳至主要内容

[pkg] go-redis 筆記

基本使用

建立 client

/**
* Source
* https://betterstack.com/community/guides/scaling-go/redis-caching-golang/
* https://ithelp.ithome.com.tw/articles/10249929
**/
func NewClient(ctx context.Context) *redis.Client {
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "",
DB: 0,
})

// Perform basic diagnostic to check if the connection is working
pong, err := rdb.Ping(ctx).Result()
if err != nil {
log.Fatalln("Redis connection was refused")
}

fmt.Println(pong)
return rdb
}

func main() {
ctx := context.Background()
rdb := NewClient(ctx)

// Ensure that the connection is properly close gracefully
defer rdb.Close()
}

Set:使用 client 設值與更新值

Update

在 Redis 中,更新資料也是用 SET

/**
* Source
* https://betterstack.com/community/guides/scaling-go/redis-caching-golang/
* https://ithelp.ithome.com.tw/articles/10249929
**/
func main() {
ctx := context.Background()
rdb := NewClient(ctx)
defer rdb.Close()

// 設成 0 表示不會過期
err := rdb.Set(ctx, "FOO", "BAR", 0).Err()
// // highlight-end
if err != nil {
fmt.Println("Failed to add FOO <> BAR key-value pair")
return
}

rdb.Set(ctx, "INT", 5, 0)
rdb.Set(ctx, "FLOAT", 5.5, 0)
rdb.Set(ctx, "EXPIRING", 15, 30*time.Minute)

// set struct data
type Person struct {
Name string `redis:"name"`
Age int `redis:"age"`
}
rdb.HSet(ctx, "STRUCT", Person{"John Doe", 15})
}

Get:使用 client 取值

/**
* Source
* https://betterstack.com/community/guides/scaling-go/redis-caching-golang/
* https://ithelp.ithome.com.tw/articles/10249929
**/
func main() {
ctx := context.Background()
rdb := NewClient(ctx)
defer rdb.Close()

// 取值
result, err := rdb.Get(ctx, "FOO").Result()
if err != nil {
log.Println("client.Get failed", err)
}

// 取值並判斷值是否存在(字串)
result, err = rdb.Get(ctx, "BAR").Result()
if err == redis.Nil {
fmt.Println("Key BAR not found in Redis cache")
} else if err != nil {
fmt.Println("client.Get failed", err)
} else {
fmt.Printf("BAR has value %s\n", result)
}

// 讀取 Int
intValue, err := rdb.Get(ctx, "INT").Int()
if err != nil {
fmt.Println("Key INT not found in Redis cache")
} else {
fmt.Printf("INT has value %d\n", intValue)
}

// 讀取 struct data
var person Person
err = rdb.HGetAll(ctx, "STRUCT").Scan(&person)
if err != nil {
fmt.Println("Key STRUCT not found in Redis cache")
} else {
fmt.Printf("STRUCT has value %+v\n", person)
}
}

Del:刪除資料

/**
* Source
* https://betterstack.com/community/guides/scaling-go/redis-caching-golang/
**/
func main() {
ctx := context.Background()
rdb := NewClient(ctx)
defer rdb.Close()

rdb.Set(ctx, "FOO", "BAR", 0)
result, err := rdb.Get(ctx, "FOO").Result()
if err != nil {
fmt.Println("FOO not found")
} else {
fmt.Printf("FOO has value %s\n", result)
}

// Deleting the key "FOO" and its associated value
rdb.Del(ctx, "FOO")
result, err = rdb.Get(ctx, "FOO").Result()
if err != nil {
fmt.Println("FOO not found")
} else {
fmt.Printf("FOO has value %s\n", result)
}
}

參考