go-redis模块对Redis进行批量操作

Jackey Golang, Redis 3,505 次浏览 , 没有评论

go-redis对redis执行批量操作的类是Pipeliner,具体示例如下.

运行该示例可在redis服务端依次接收到:

  1. MULTI
  2. incr tx_pipeline_counter
  3. expire tx_pipeline_counter 3600
  4. 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

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

Go