Created
January 22, 2019 06:11
-
-
Save gruzovator/16311ecdc6889c742c5fbe3bc1ef44b0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"errors" | |
"fmt" | |
"github.com/go-redis/redis" | |
"log" | |
"reflect" | |
) | |
type redisItemCallback func(key string, value interface{}) error | |
func MGet(redisClient *redis.Client, IDs interface{}, itemCallback redisItemCallback) error { | |
rv := reflect.ValueOf(IDs) | |
if rv.Len() == 0 { | |
return nil | |
} | |
redisKeys := make([]string, 0, rv.Len()) | |
for i := 0; i < rv.Len(); i++ { | |
redisKeys = append(redisKeys, fmt.Sprint(rv.Index(i))) | |
} | |
values, err := redisClient.MGet(redisKeys...).Result() | |
if err != nil { | |
return err | |
} | |
for i, v := range values { | |
if err := itemCallback(redisKeys[i], v); err != nil { | |
return err | |
} | |
} | |
return nil | |
} | |
func main() { | |
client := redis.NewClient(&redis.Options{ | |
Addr: "localhost:6379", | |
Password: "", // no password set | |
DB: 0, // use default DB | |
}) | |
if err := client.Ping().Err(); err != nil { | |
log.Fatal(err) | |
} | |
type myType struct { | |
ID int | |
Info string | |
} | |
myMap := make(map[int]myType) | |
err := MGet(client, []int{1, 2}, func(key string, v interface{}) error { | |
strVal, ok := v.(string) | |
if !ok { | |
return errors.New("invalid redis response type") | |
} | |
var myTypeVal myType | |
if err := json.Unmarshal([]byte(strVal), &myTypeVal); err != nil { | |
return fmt.Errorf("unexpected redis value format for key: %s", key) | |
} | |
myMap[myTypeVal.ID] = myTypeVal | |
return nil | |
}) | |
if err != nil { | |
log.Fatal(err) | |
} | |
fmt.Println(myMap) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment