6

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)
Vinay Sawant
  • 368
  • 2
  • 7
  • 23

2 Answers2

16

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)
}
Charlie Tumahai
  • 113,709
  • 12
  • 249
  • 242
6

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

akokskis
  • 1,486
  • 15
  • 32
taraf
  • 777
  • 2
  • 10
  • 28
  • question, does the `KEYS` operation block requests to DB0, or will it block all DB requests, not just the one being queried? As redis is single threaded, i have a feeling the answer is a yes... `KEYS` will block requests to all DBs – Cmag May 14 '20 at 00:00