标签:protocl string cmd redis redisClient golang func 客户端
目的
通过搭建一个高可用的redis客户端来学习redis,go语言,以及go一些设计模式
参考资料
go-redis源码
《redis设计与实现》
学习思路
循环渐进,从最简单的一步步迭代
一个最简单的能跑通的redis客户端例子
package main
import (
"fmt"
"net"
"strings"
)
type options struct {
Network string
Addr string
}
func (p *options) init() {
if p.Addr == "" {
p.Addr = "127.0.0.1:6379"
}
if p.Network == "" {
p.Network = "tcp"
}
}
//redis struct
type redisClient struct {
opt options
conn net.Conn
sendCmd string
reply string
}
func (c *redisClient) connect() {
conn, err := net.Dial(c.opt.Network, c.opt.Addr)
if err != nil {
fmt.Println("connect err ", err)
}
c.conn = conn
}
func (c *redisClient) sendCommand(cmd string) string {
c.formatCommand(cmd)
c.write()
return c.getReply()
}
func (c *redisClient) formatCommand(cmd string) {
var protocl_cmd string
cmd_argv := strings.Fields(cmd)
protocl_cmd = fmt.Sprintf("*%d\r\n", len(cmd_argv))
for _, arg := range cmd_argv {
protocl_cmd += fmt.Sprintf("$%d\r\n", len(arg))
protocl_cmd += arg
protocl_cmd += "\r\n"
}
//redis服务器接受的命令协议
fmt.Printf("%q\n", protocl_cmd)
c.sendCmd = protocl_cmd
}
func (c *redisClient) write() {
c.conn.Write([]byte(c.sendCmd))
c.sendCmd = ""
}
func (c redisClient) getReply() string {
byte_len := 1024 * 16
reply := make([]byte, byte_len)
//暂时简化一次输出完
c.conn.Read(reply)
return string(reply)
}
func NewClient(opt options) *redisClient {
c := redisClient{
opt: opt,
}
c.opt.init()
c.connect()
return &c
}
func main() {
c := NewClient(options{
Addr: "127.0.0.1:6379",
})
rep := c.sendCommand("set hello world")
fmt.Println(rep)
}
上面这个例子,暂时没考虑读写循环,错误处理,主要实现了发送redis服务器命令协议内容,以及客户端连接
标签:protocl,string,cmd,redis,redisClient,golang,func,客户端 来源: https://blog.csdn.net/u014270740/article/details/89929972
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。