在上一篇《Go语言:字节流读写(io.Reader/io.Writer)的示例之redis读写》的基础上,本篇把缓冲区加上去。
bufio包有两个New函数,分别是在任意io.Reader和io.Writer的基础上再包装一层缓冲区得到bufio.Reader和bufio.Writer。 func NewReader(rd io.Reader) *Reader func NewWriter(w io.Writer) *Writer
下面的代码利用bufio来执行两条redis客户端操作,需要注意的是bufio.Writer在调用完Write之后还需要调用Flush清空缓冲区。
127.0.0.1:6380> set key 75
OK
127.0.0.1:6380> get key
"75"
package main
import (
"fmt"
"io"
"bufio"
"net"
)
func exec(wr *bufio.Writer, rd *bufio.Reader, cmd string) (string, error) {
var err error
_, err = wr.Write([]byte(cmd))
if err != nil {
return "", err
}
wr.Flush()
var p []byte = make([]byte, 1024, 1024)
_, err = rd.Read(p)
if err != nil && err != io.EOF {
return "", err
}
return string(p), nil
}
func main() {
var conn net.Conn
var err error
conn, err = net.Dial("tcp", "127.0.0.1:6380")
if err != nil {
fmt.Printf("err=%v\n", err)
return
}
var reply string
wr := bufio.NewWriter(conn)
rd := bufio.NewReader(conn)
//set key 75
reply, err = exec(wr, rd, "*3\r\n$3\r\nSET\r\n$3\r\nkey\r\n$2\r\n75\r\n")
fmt.Printf("set key 75's reply=%s err=%v\n", reply, err)
//get key
reply, err = exec(wr, rd, "*2\r\n$3\r\nGET\r\n$3\r\nkey\r\n")
fmt.Printf("get key's reply=%s err=%v\n", reply, err)
}
输出:
set key 75's reply=+OK
err=<nil>
get key's reply=$2
75
err=<nil>