Skip to content

Instantly share code, notes, and snippets.

@benhenryhunter
Last active February 23, 2023 22:17
Show Gist options
  • Save benhenryhunter/aea8964ab6851dac8bda427741cdcb2d to your computer and use it in GitHub Desktop.
Save benhenryhunter/aea8964ab6851dac8bda427741cdcb2d to your computer and use it in GitHub Desktop.
Exploring go-redis pipelines
package main
import (
"context"
"fmt"
"time"
"github.com/redis/go-redis/v9"
)
func main() {
rdb, err := connectRedis(":6379", 10)
if err != nil {
panic(err)
}
ctx := context.Background()
if _, err := rdb.HSet(ctx, "test-stuff", "key", "value", "key2", "value").Result(); err != nil {
panic(err)
}
pipe := rdb.Pipeline()
c := pipe.HGetAll(ctx, "test-stuff")
_, err = pipe.Exec(ctx)
if err != nil {
panic(err)
}
fmt.Printf("%+v\n", c.Val())
m2, err := rdb.HGetAll(ctx, "test-stuff").Result()
if err != nil {
panic(err)
}
// The value is available only after Exec is called.
// fmt.Printf("%+v\n", m)
fmt.Printf("%+v\n", m2)
}
func connectRedis(redisURI string, connectionPoolLimit int) (*redis.Client, error) {
redisClient := redis.NewClient(&redis.Options{
PoolSize: connectionPoolLimit,
Addr: redisURI,
MinIdleConns: connectionPoolLimit / 2,
PoolTimeout: 1 * time.Minute,
ReadTimeout: 2 * time.Second,
WriteTimeout: 30 * time.Second,
})
if _, err := redisClient.Ping(context.Background()).Result(); err != nil {
// unable to connect to redis
return nil, err
}
return redisClient, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment