【问题标题】:Golang fasthttp very slow with requestGolang fasthttp请求非常慢
【发布时间】:2017-02-14 16:29:30
【问题描述】:

我正在使用 fasthttp 包构建一个 Rest API。我有一个用来衡量性能的测试路线:

package main

import (
    "github.com/valyala/fasthttp"
    "runtime"
)

func main() {

    runtime.GOMAXPROCS(8)
    m := func(ctx *fasthttp.RequestCtx) {
        switch string(ctx.Path()) {
        case "/test":
            test(ctx)
        default:
            ctx.Error("not found", fasthttp.StatusNotFound)
        }
    }

    fasthttp.ListenAndServe(":80", m)
}

func test(ctx *fasthttp.RequestCtx) {
    println("HERE")
}

如果我向该路由发送请求,则需要 10 多秒才能到达测试函数中的 println("HERE")

我在 Node.js 中构建了一个类似的端点,这个完全相同的功能和路由需要 126 毫秒。
为什么在 Go 中调用这条路由指向的函数需要这么长时间?

【问题讨论】:

  • 我刚刚使用您的确切代码进行了测试,几乎不需要时间(不到 1 秒)即可到达 println("HERE")。您的测试设置有多准确?
  • 尝试我的示例并发布(添加评论)代码(2)输出

标签: rest http go fasthttp


【解决方案1】:

对我来说,100000 http.Head 只需要 7.9454545 秒(每 http.Head 需要 79.454545us,运行这 1 和 2 个代码时,只有 2 个核心 CPU,负载为 77%)。

你不需要runtime.GOMAXPROCS(8),用fmt.Println()代替println()

1- 试试这个:

package main

import (
    "fmt"

    "github.com/valyala/fasthttp"
)

func main() {
    m := func(ctx *fasthttp.RequestCtx) {
        switch string(ctx.Path()) {
        case "/test":
            test(ctx)
        default:
            fmt.Println(i)
            ctx.Error("not found", fasthttp.StatusNotFound)
        }
    }
    fasthttp.ListenAndServe(":80", m)
}

func test(ctx *fasthttp.RequestCtx) {
    i++
}

var i int = 0

输出:

100000

2- 使用此获取:

package main

import (
    "fmt"
    "net/http"
    "time"
)

func main() {
    t := time.Now()
    for i := 0; i < 100000; i++ {
        read(`http://localhost/test`)
    }
    fmt.Println(time.Since(t))
    read(`http://localhost/`)
}

func read(url string) {
    _, err := http.Head(url)
    if err != nil {
        fmt.Println(err)
    }
}

输出:

7.9454545s

3-This code 的输出:

8.6294936s

【讨论】:

    猜你喜欢
    • 2020-01-17
    • 1970-01-01
    • 2018-03-22
    • 2014-11-05
    • 1970-01-01
    • 2015-05-20
    • 1970-01-01
    • 2016-01-21
    • 2020-04-17
    相关资源
    最近更新 更多