【中间件go client系列】redis的go client使用

有时候需要对key值的进行统计,这时候就需要写个工具类。
用法如下:

./keys_count_tool -address 'ip:6379' -filename 'userinfo_key.txt' -findkeys '*_USERINFOCENTER_*'

代码如下:

package main

import (
"flag"
"fmt"
"github.com/go-redis/redis"
"os"
)

var address string
var filename string
var findkeys string

func init() {
flag.StringVar(&address, "address", "redis server ip and port", "-address")
flag.StringVar(&filename, "filename", "file name", "-filename")
flag.StringVar(&findkeys, "findkeys", "find keys", "-findkeys")
}
func main() {
flag.Parse()
client := redis.NewClient(&redis.Options{
Addr: address,
Password: "", // no password set
DB: 0, // use default DB
})

var cursor uint64
var n int
file, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0777)
if err != nil {
fmt.Println("文件打开失败", err)
}
//及时关闭file句柄
defer file.Close()
for {
var keys []string
var err error
//*扫描所有key,每次20条

keys, cursor, err = client.Scan(cursor, findkeys, 20).Result()
if err != nil {
panic(err)
}
for _, key := range keys {
data := key + "\n"
n, err := file.Write([]byte(data))
if err == nil && n < len(data) {
fmt.Println("写入文件失败", err)
}
}
n += len(keys)
fmt.Printf("\nfound %d keys\n", n)
if cursor == 0 {
break
}
}
}