sqler sql 转rest api 源码解析(二) resp 协议

resp 协议主要是方便使用redis 客户端进行连接,resp 主要是依赖 tidwall/redcon golang redis 协议包

resp 服务说明

server_resp.go 文件,干的事情比较简单,就是redis command 的支持,包含了几个内置的
ping select help quit echo, 以及宏相关的list 以及宏调用的command

代码

server_resp.go

  • 注册redis 协议服务
 
func initRESPServer() error {
  return redcon.ListenAndServe(
    *flagRESPListenAddr,
    func(conn redcon.Conn, cmd redcon.Command) {
      // handles any panic
      defer (func() {
        if err := recover(); err != nil {
          conn.WriteError(fmt.Sprintf("fatal error: %s", (err.(error)).Error()))
        }
      })()
 
 
  • 协议解析
    内置协议的处理help echo ping 。。。
    比较简单,就是写数据,都是字符串类型的
 
// internal command to pick a database
      if todoNormalized == "select" {
        conn.WriteString("OK")
        return
      }
      // internal ping-pong
      if todoNormalized == "ping" {
        conn.WriteString("PONG")
        return
      }
      // ECHO <args ...>
      if todoNormalized == "echo" {
        conn.WriteString(strings.Join(args, " "))
        return
      }
 
 

宏调用
list command 命令,主要是调用macrosManager 的list 方便,返回宏的列表

 
// HELP|INFO|LIST
      if todoNormalized == "list" || todoNormalized == "help" || todoNormalized == "info" {
        conn.WriteArray(macrosManager.Size())
        for _, v := range macrosManager.List() {
          conn.WriteBulkString(v)
        }
      }
 
 

宏方便指定
核心是commandExecMacro

 
macro := macrosManager.Get(todo)
      if nil == macro {
        conn.WriteError("not found")
        conn.Close()
        return
      }
      var input map[string]interface{}
      if len(args) > 0 {
        json.Unmarshal([]byte(args[0]), &input)
      }
      // handle our command
      commandExecMacro(conn, macro, input)
 
 

commandExecMacro 方法如下:

func commandExecMacro(conn redcon.Conn, macro *Macro, input map[string]interface{}) {
  // 调用macro 的call,call 包含了宏生命周期中的处理,注意input 数据是一个json 对象数据,所以通过
  redis 客户端调用宏的时候数据需要json 序列化
  out, err := macro.Call(input)
  if err != nil {
    conn.WriteArray(2)
    conn.WriteInt(0)
    j, _ := json.Marshal(err.Error())
    conn.WriteBulk(j)
    return
  }
  jsonOUT, _ := json.Marshal(out)
  conn.WriteArray(2)
  conn.WriteInt(1)
  conn.WriteBulk(jsonOUT)
}
 
 

参考资料

https://github.com/tidwall/redcon
https://github.com/alash3al/sqler/blob/master/server_resp.go

posted on   荣锋亮  阅读(513)  评论(0编辑  收藏  举报

编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2014-01-14 转 微软发布TX(LINQ To Logs And Traces)
2014-01-14 nginx php 配置
2014-01-14 如何判断一个请求是否为AJAX请求
2014-01-14 使用rewrite 让php 实现类似asp.net 的IHttpModule 进行带参数js文件的参数获取

导航

< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5
点击右上角即可分享
微信分享提示