Redisの使い方を毎回忘れるので
GitHub – redis/go-redis: Redis Go client
Redis Go client. Contribute to redis/go-redis development by creating an account on GitHub.
目次
set, get
package main
import (
"context"
"fmt"
"time"
"github.com/redis/go-redis/v9"
)
func main() {
rcli := redis.NewClient(&redis.Options{
Addr: "localhost:16379",
Password: "",
DB: 0,
})
ctx := context.Background()
if err := rcli.Ping(context.Background()).Err(); err != nil {
panic(err)
}
// key, value, expのセット
if err := rcli.Set(ctx, "test-key", "test-value", 100*time.Millisecond).Err(); err != nil {
panic(err)
}
got, err := rcli.Get(ctx, "test-key").Result()
if err == redis.Nil {
fmt.Println("key not exist:", err)
} else if err != nil {
panic(err)
} else {
fmt.Println("val:", got) // val: test-value
}
// 有効期限を過ぎてみる
time.Sleep(150 * time.Millisecond)
got, err = rcli.Get(ctx, "test-key").Result()
if err == redis.Nil {
fmt.Println("key not exist:", err) // key not exist: redis: nil
} else if err != nil {
panic(err)
} else {
fmt.Println("val:", got)
}
}
Get All Keys
var cursor uint64
for {
fmt.Println("in loop")
var keys []string
var err error
// 最後の0は「何個ずつ取得する?」
keys, cursor, err = rcli.Scan(ctx, cursor, "prefix*", 0).Result()
if err != nil {
panic(err)
}
for _, key := range keys {
fmt.Println("key", key)
}
if cursor == 0 { // no more keys
break
}
}
コメント