Web 框架的基本观点,为什么 httprouter 比默认多路复用器工作得更快

问题描述 投票:0回答:0

Gin 是一个用 Go 编写的 Web 框架。它具有类似马提尼酒的 API,由于 httprouter,性能最高可提高 40 倍。

那是他们在 Gin 框架主页上所说的。我很好奇他们采用了哪一部分和什么技术来使速度提高 40 倍。

在我的理解中,在任何网络框架中处理请求的方式都是相似的。

  1. 服务器收到请求,启动一个 goroutine 进行连接。
  2. 在多路复用之前为 auth 或其他东西运行服务处理程序。 (一般称为中间件或k8s中的handlerchain)
  3. 多路复用,将请求定向到附加到 url 模式的处理程序。
  4. 处理,返回结果

我不知道这是否正确,但我认为多路复用器是不同 Web 服务器(框架)之间唯一的速度差异。

golang标准库中默认的multiplexer定义如下,使用hash table查找handler。

type ServeMux struct {
    mu    sync.RWMutex
    m     map[string]muxEntry
    es    []muxEntry // slice of entries sorted from longest to shortest.
    hosts bool       // whether any patterns contain hostnames
}

type muxEntry struct {
    h       Handler
    pattern string
}


httprouter 使用基数树,定义为

type Router struct {

trees map[string]*node

...

}

type node struct {
    path      string
    wildChild bool
    nType     nodeType
    maxParams uint8
    priority  uint32
    indices   string
    children  []*node
    handle    Handle
}

那么问题来了:既然都是用hash table来找handler或者radix tree的一个节点,为什么httprouter跑得更快?他们是用什么方法制作的?

algorithm go hashtable web-frameworks httprouter
© www.soinside.com 2019 - 2024. All rights reserved.