Go语言:字节流读写(io.Reader/io.Writer)的示例之redis读写

 读写字节流的两个基本接口定义如下:

type Reader interface {
    Read(p []byte) (n int, err error)
}

type Writer interface {
    Write(p []byte) (n int, err error)
}

net.Conn这个接口也定义了上述两个函数,因此即是io.Reader接口也是io.Writer接口。

下面的代码利用net.Conn来执行两条redis客户端操作:

127.0.0.1:6380> set key 75
OK
127.0.0.1:6380> get key
"75"
package main

import (
        "fmt"
        "io"
        "net"
)

func exec(wr io.Writer, rd io.Reader, cmd string) (string, error) {
        var err error
        _, err = wr.Write([]byte(cmd))
        if err != nil {
                return "", err
        }

        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
        //set key 75
        reply, err = exec(conn, conn, "*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(conn, conn, "*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>

如果需要加入缓冲区请见另外一篇《Go语言:带有缓冲区的字节流读写(bufio.Reader/bufio.Writer)的示例之redis读写

Redis文本协议详见《Redis Protocol specification

 

Guess you like

Origin blog.csdn.net/pengpengzhou/article/details/108386356