Go Redis Pipeline Batch Commands
Batch independent Redis commands into pipelines and transactions, measuring round-trip savings and verifying atomic MULTI execution.
Code
package main
import (
"context"
"fmt"
"time"
"github.com/redis/go-redis/v9"
)
func seedAndMeasure(ctx context.Context, client *redis.Client) error {
keys := []string{"metric:hits", "metric:misses", "metric:errors"}
// 独立命令走管道:一次网络往返
pipe := client.Pipeline()
incrCmds := make([]*redis.IntCmd, len(keys))
for i, key := range keys {
incrCmds[i] = pipe.Incr(ctx, key)
}
if _, err := pipe.Exec(ctx); err != nil {
return fmt.Errorf("pipeline exec: %w", err)
}
// 事务管道:命令打包进 MULTI/EXEC 原子执行
tx := client.TxPipeline()
expireCmds := make([]*redis.BoolCmd, len(keys))
for i, key := range keys {
expireCmds[i] = tx.Expire(ctx, key, time.Hour)
}
if _, err := tx.Exec(ctx); err != nil {
return fmt.Errorf("tx exec: %w", err)
}
for i, key := range keys {
fmt.Printf("%s=%d expires=%v\n",
key, incrCmds[i].Val(), expireCmds[i].Val())
}
return nil
}
func main() {
client := redis.NewClient(&redis.Options{
Addr: "127.0.0.1:6379",
PoolSize: 10,
ReadTimeout: 500 * time.Millisecond,
})
defer client.Close()
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
if err := seedAndMeasure(ctx, client); err != nil {
fmt.Println("failed:", err)
}
}The path through the code
Go Redis Pipeline Batch Commands keeps everything in the functions seedAndMeasure and main.
Iteration happens inside for i, key := range keys — everything outside it runs once. Nothing falls through silently — 3 checkpoints test err != nil on the way through. The function registers its cleanup up front with defer, so no exit path forgets it.
Points of care
- Dependency check:
github.com/redis/go-redis/v9— not built-in, must be present in the project. - The function reports failure by returning
error— callers branch on it before touching other results.
Putting it to use
The primary signature is func seedAndMeasure(ctx context.Context, client *redis.Client) error
Running the file prints labeled results such as failed: — each operation’s effect is visible in the output.
Launch the file; main takes over and steps through seedAndMeasure.
Core lines
return fmt.Errorf("pipeline exec: %w", err)
return fmt.Errorf("tx exec: %w", err)
for i, key := range keys {
incrCmds[i] = pipe.Incr(ctx, key)
}
Interactive Tools for This Topic
FAQ
- What is the error handling style?
- The Go way: `err` comes back from each call, and 3 checkpoints here test it before proceeding.
- What does this need from the package registry?
- These are real dependencies: `github.com/redis/go-redis/v9`. Without it the snippet will not load.
Report a problem with this exampleOpens a pre-filled issue on GitHub.