欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Golang redis(五)redigo pipline管道

程序员文章站 2022-05-08 16:02:40
...

redis管道可以用来一次性执行多个命令, 可以节省网络带宽,同时对于应用的性能也有一定的提升

pipline 管道

redigo支持管道: 使用Send, Flush and Receive 三个函数

Send(commandName string, args ...interface{}) error
Flush() error
Receive() (reply interface{}, err error)

send将命令发送到缓冲区中

flush刷新缓冲区,将命令发送到redis服务器

receive负责处理接收到的消息内容, 注意:receive一次只从结果中拿出一个send的命令进行处理

例如

c.Send("SET", "foo", "bar")
c.Send("GET", "foo")
c.Flush()
c.Receive() // reply from SET
v, err = c.Receive() // reply from GET

示例:

package main

import (
   "fmt"
   "github.com/gomodule/redigo/redis"
   "log"
)

func echoReceive(res interface{}, err error){
   if err != nil{
      fmt.Println(err)
   }else {
      if res != nil{
         fmt.Printf("---------  ")
         fmt.Println(string(res.([]byte)))
      }else {
         fmt.Println(res)
      }

   }
}

func main() {
   c1, err := redis.Dial("tcp", "127.0.0.1:6379")
   if err != nil {
      log.Fatalln(err)
   }
   defer c1.Close()

   c1.Send("Get", "my_test")
   c1.Flush()
   echoReceive(c1.Receive())

   c1.Send("Get", "my_test2")
   c1.Flush()
   echoReceive(c1.Receive())

   c1.Send("Get", "my_test")
   c1.Send("Get", "my_test2")
   c1.Send("Get", "my_test3")
   c1.Flush()
   echoReceive(c1.Receive())
   echoReceive(c1.Receive())
   echoReceive(c1.Receive())
}

输出结果:

---------  this is test
<nil>
---------  this is test
<nil>
---------  this is test3

另外也提供了Do方法

Do方法结合了Send,Flush和Receive方法的功能。Do方法首先写入命令并刷新输出缓冲区。接下来,Do方法接收所有待处理的回复,包括刚刚发送的命令的回复。如果收到的任何回复都是错误,则Do返回错误。如果没有错误,则Do返回最后一个回复。如果Do方法的命令参数为“”,则Do方法将刷新输出缓冲区并接收挂起的回复而不发送命令

例如:

c.Send("MULTI")
c.Send("INCR", "foo")
c.Send("INCR", "bar")
r, err := c.Do("EXEC")
fmt.Println(r) // prints [1, 1]

示例:

package main

import (
   "fmt"
   "github.com/gomodule/redigo/redis"
)


func main() {
   c1, err := redis.Dial("tcp", "127.0.0.1:6379")
   if err != nil {
      log.Fatalln(err)
   }
   defer c1.Close()

	var value1 string
	var value2 string
	var value3 string

	c1.Send("MULTI")
	c1.Send("Get", "my_test")
	c1.Send("Get", "my_test2")
	c1.Send("Get", "my_test3")
	r, err := redis.Values(c1.Do("EXEC"))
	//fmt.Println(r)
	if _, err := redis.Scan(r, &value1, &value2, &value3); err == nil {
		fmt.Println(value1)
		fmt.Println(value2)
		fmt.Println(value3)
	}
}

输出:

this is test

this is test3