Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use go net to implement simple redis communication protocol

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

这篇文章主要为大家展示了"如何使用go net实现简单的redis通信协议",内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下"如何使用go net实现简单的redis通信协议"这篇文章吧。

图解redis通信协议

请求协议:

请求协议一般格式:

* CR LF$ CR LF CR LF...$ CR LF CR LF

例如,一个登录命令:

*2 2-> 参数数量$4 4-> 字节数量AUTH$13password@2018

返回结果:

+OK

实际上,发送的命令为"*2\r\n$4\r\nAUTH\r\n$13\r\npassword@2018\r\n"

测试代码:

package mainimport ( "bufio" "fmt" "net" "strconv" "testing" "time")type Conn struct { // Shared conn net.Conn // Read br *bufio.Reader // Write bw *bufio.Writer}func (c *Conn) Write(cmd string, args ...string) error { _, err := c.bw.WriteString("*" + strconv.Itoa(1 + len(args)) + "\r\n") if err != nil { return err } _, err =c.bw.WriteString("$" + strconv.Itoa(len(cmd)) + "\r\n" + cmd + "\r\n") if err != nil { return err } for _, v := range args { _, err :=c.bw.WriteString("$" + strconv.Itoa(len(v)) + "\r\n" + v + "\r\n") if err != nil { return err } } err = c.bw.Flush() if err != nil { return err } return nil}func TestDail(t *testing.T) { conn,err := net.Dial("tcp","127.0.0.1:6379") if err != nil { panic(err) } var c = &Conn{ conn: conn, br : bufio.NewReader(conn), bw: bufio.NewWriter(conn), } err = c.Write("AUTH","password@2018") if err != nil { panic(err) } p, err := c.br.ReadSlice('\n') if err != nil { panic(err) } fmt.Println(string(p)) err = c.Write("SELECT", "5") if err != nil { panic(err) } p, err = c.br.ReadSlice('\n') if err != nil { panic(err) } fmt.Println(string(p)) err = c.Write("keys","*") if err != nil { panic(err) } buffer := make([]byte, 4096) n, err := c.br.Read(buffer) if err != nil { panic(err) } fmt.Println(string(buffer[:n]))}

运行结果

+OK

+OK

*9

$4

set2

$1

s

$4

set3

$7

string3

$4

int1

$4

test

$7

string2

$7

string1

$7

string4

以上是"如何使用go net实现简单的redis通信协议"这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注行业资讯频道!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report