1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
| package main
import ( "bufio" "errors" "fmt" "io" "net" "strconv" )
type RedisClient struct { conn net.Conn writer *bufio.Writer reader *bufio.Reader }
func main() { conn, err := net.Dial("tcp", "127.0.0.1:6379") if err != nil { fmt.Println("连接redis失败", err) } client := RedisClient{conn: conn, writer: bufio.NewWriter(conn), reader: bufio.NewReader(conn)} defer client.conn.Close() client.sendRequest([]string{"set", "name", "方块"}) client.sendRequest([]string{"LRANGE", "tlist", "0", "-1"})
}
func (client *RedisClient) sendRequest(args []string) interface{} {
length := len(args) firstCommand := fmt.Sprintf("%s%d", "*", length) client.writeCommand(firstCommand) for _, s := range args { n := len(s) client.writeCommand("$" + strconv.Itoa(n)) client.writeCommand(s) println(n, s) } response := client.handleResponse() return response
}
func (client *RedisClient) writeCommand(s string) { client.conn.Write([]byte(s + "\r\n"))
}
func (client *RedisClient) handleResponse() interface{} {
r, _, _ := client.reader.ReadRune() flag := string(r) fmt.Println("第一个操作数:" + flag) switch flag { case "+": return client.ReadLine() case "-": return client.ReadLine() case ":": line := client.ReadLine() res, _ := strconv.Atoi(line) return res case "$": readRune := client.ReadLine() length := string(readRune) if length == "-1" { return nil } else if length == "0" { return "" } lll, _ := strconv.Atoi(length) bytes := make([]byte, lll+2) n, _ := client.reader.Read(bytes) return string(bytes[:n]) case "*": return client.readBulkString() default: return errors.New("错误") } }
func (client *RedisClient) ReadLine() string { bytes, _, _ := client.reader.ReadLine() return string(bytes) }
func (client *RedisClient) ReadToEnd() string {
var size = 1024 bytes := make([]byte, size) var temp = "" for { n, err := client.reader.Read(bytes) temp += string(bytes[:n]) if err == io.EOF || n == 0 || n < size { break }
}
return temp } func (client *RedisClient) readBulkString() interface{} {
counts, _ := strconv.Atoi(client.ReadLine()) if counts <= 0 { return nil } var lists []interface{} for i := 0; i < counts; i++ { res := client.handleResponse() lists = append(lists, res) }
return lists
}
|