Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get All keys From redis in go

Tags:

redis

go

redigo

How to get all keys of Redis in db and store it in list or array in golang using redigo?

redisPool := redis.NewPool(func() (redis.Conn, error) {
    con, err := redis.Dial("tcp", *redisAddress)
    con.Do("SELECT", 0)
    if err != nil {
        return nil, err
    }
    return con, err
}, *maxConnections)
fmt.Println("Redis Connection Established...!")
con := redisPool.Get()

//defer con.Close()
fmt.Println("Redis Connected...!")
//var sl []string = make([]string, len, cap)
var ab interface{}
ab, errA := con.Do("Keys", "*")
fmt.Println(ab)
fmt.Println(errA)
like image 829
Vinay Sawant Avatar asked Jul 17 '15 10:07

Vinay Sawant


2 Answers

Use the Strings function to convert the result to a slice of strings:

keys, err := redis.Strings(cn.Do("KEYS", "*"))
if err != nil {
    // handle error
}
for _, key := range keys {
   fmt.Println(key)
}
like image 171
Bayta Darell Avatar answered Nov 15 '22 07:11

Bayta Darell


Since Redis only has one thread, the KEYS command will block all other requests until it has finished, so it's not a good approach for production. Instead, use SCAN. see SCAN documentation here

like image 37
taraf Avatar answered Nov 15 '22 08:11

taraf