I am using redis.v5. I want to read all redis keys value in one go, value of each key is hashMap i.e map[string]string. So I am using Redis transaction functionality of MULTI/EXEC. I have a function which does this, I am getting the response like this:
[hgetall x: map[VIN:POIUYTRUT4567ASWQ beaconID:1123VBG132 customerName:Amit displayLocation:waiting launge timestamp:2017-12-26T08:51:21.509Z] y: map[VIN:POIUYTRUT4567qweD beaconID:1123VBG13222 customerName:prameet displayLocation:waiting launge timestamp:2017-12-26T08:51:21.509Z]]
my function is this:
func GetListOfValuesForKeys( keys []string,address, password string,db int) ([]map[string]string, error) {
redisClient, err := redis.NewClient(loadRedisOptions(address, password, db))
if err != nil {
return nil, err
}
pipe := redisClient.TxPipeline()
for _, val := range keys {
pipe.HGetAll(val)
}
var data []map[string]string
cmder, err := pipe.Exec()
if err != nil {
return nil, err
}
fmt.Printf("
|**********res %++v**************|
", cmder)
return data, nil
}
func loadRedisOptions(address, password string, db int) *redis.Options
{
return &redis.Options{
Addr: address,
Password: password,
DB: db,
}
}
Now is there any inbuilt method in redis.v5 which can Unmarshal the pipe.Exec() method's response to map[string]string. pipe.Exec() method returns a slice of given below interface ([]Cmder):
type Cmder interface {
args() []interface{}
arg(int) string
name() string
readReply(*pool.Conn) error
setErr(error)
readTimeout() *time.Duration
Err() error
fmt.Stringer
}
This is the definition of Exec:
func (c *Pipeline) Exec() ([]Cmder, error)
and Cmder
implements
type Cmder interface {
Name() string
Args() []interface{}
Err() error
fmt.Stringer
// contains filtered or unexported methods
}
and
Cmder
implements fmt.Stringer
which is defined as
type Stringer interface {
String() string
}
where
Stringer is implemented by any value that has a String method, which defines the “native” format for that value. The String method is used to print values passed as an operand to any format that accepts a string or to an unformatted printer such as Print.
https://godoc.org/fmt#Stringer
Therefore,
You can access values by doing:
Cmder.String()
So what you're looking for is something like this:
cmdMap := map[string]string
cmder, err := pipe.Exec()
if err != nil {
return nil, err
}
for cmd := range cmder {
key := cmd.Name() // maybe use cmd.Args() to distinguish
cmdMap[key] = cmd.String()
}
return cmdMap, nil
Let me know if this doesn't work.