Last active
August 6, 2018 06:44
-
-
Save samaita/b79bdb2459acf36f8721a617c0ee4ea2 to your computer and use it in GitHub Desktop.
Pipeline with Redigo
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 redis | |
import ( | |
redigo "github.com/garyburd/redigo/redis" | |
) | |
// HMGET is a common usage of Redis command HMGET | |
func (r *redis) HMGET(key string, fields ...string) ([]string, error) { | |
conn := r.Pool.Get() | |
defer conn.Close() | |
cmd := append([]string{key}, fields...) | |
payload := make([]interface{}, len(cmd)) | |
for n, c := range cmd { | |
payload[n] = c | |
} | |
result := make(map[string]string) | |
resp, err := redigo.Strings(conn.Do("HMGET", payload...)) | |
if err != nil { | |
return nil, err | |
} | |
return resp, nil | |
} | |
// HMGETP is HMGET with Pipeline | |
func (r *redis) HMGETP(keys []string, fields ...string) ([]interface{}, error) { | |
conn := r.Pool.Get() | |
defer conn.Close() | |
// open pipeline, generate chain of commands | |
for _, key := range keys { | |
cmd := append([]string{key}, fields...) | |
payload := make([]interface{}, len(cmd)) | |
for n, c := range cmd { | |
payload[n] = c | |
} | |
// Send writes the command to the connection's output buffer | |
if err := conn.Send("HMGET", payload...); err != nil { | |
return nil, err | |
} | |
} | |
// Flush flushes the connection's output buffer to the server. | |
if err := conn.Flush(); err != nil { | |
return nil, err | |
} | |
//Receive reads a single reply from the server. | |
replies := make([]interface{}, len(keys)) | |
for i := 0; i < len(keys); i++ { | |
reply, err := conn.Receive() | |
if err != nil { | |
return nil, err | |
} | |
replies[i] = reply | |
} | |
resp, err := redigo.Values(replies, nil) | |
if err != nil { | |
return nil, err | |
} | |
return resp, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment