go-redis对redis执行批量操作的类是Pipeliner,具体示例如下.
运行该示例可在redis服务端依次接收到:
- MULTI
- incr tx_pipeline_counter
- expire tx_pipeline_counter 3600
- EXEC
多条命令采用批量处理不止节省网络时间,同时也节省redis服务端的处理时间。
package main import ( "fmt" "github.com/go-redis/redis" "time" ) func main() { client := redis.NewClient(&redis.Options{ Addr: "192.168.16.242:6379", Password: "", DB: 0, }) defer client.Close() tSaved := time.Now() test1(client) fmt.Printf("elapse: %v\n", time.Now().Sub(tSaved)) tSaved = time.Now() test2(client) fmt.Printf("elapse: %v\n", time.Now().Sub(tSaved)) } func test1(client *redis.Client) { _, _ = client.Incr("tx_pipeline_counter").Result() _ = client.Expire("tx_pipeline_counter", time.Hour) } func test2(client *redis.Client) { pipe := client.TxPipeline() _ = pipe.Incr("tx_pipeline_counter") pipe.Expire("tx_pipeline_counter", time.Hour) pipe.Exec() }
参考链接:https://blog.csdn.net/pengpengzhou/article/details/104972232