golang fasthttp服务端的简单实现

使用示例:

package main

import (
   "github.com/buaazp/fasthttprouter"
   "github.com/valyala/fasthttp"
   "log"
)

func main() {
   // 创建路由
   r := fasthttprouter.New()
   r.GET("/", Index)
   if err := fasthttp.ListenAndServe(":8080", r.Handler); err != nil {
      log.Fatalf("ListenAndServe fatal: %s\n", err)
   }
}

func Index(ctx *fasthttp.RequestCtx)  {
   ctx.WriteString("hello, fasthttp client")
}

fasthttp据说性能比 net/http 好很多,主要是以下几个方面:

  • 1.大量使用 sync.Pool 来内存复用请求处理,减少每个请求过来就新建一个协程处理
  • 2.连接复用,连接处理先从 ready字段的 workerChan 中获取 worker,没有就从 workerPool 中获取
  • 3.bytes <-> string 的转换用的 unsafe.Pointer,避免内存分配与拷贝带来的消耗

从共性上来说,fasthttp 包很多思想还是借用 net/http 的,比如路由的处理,通过 map 映射不同的 method 树,但与单纯的 net/http 不同的是,fasthttp通过 method 区分不同的路由树,类似 gin框架 思想,net/http 使用的就是 map[path]Handler,简单粗暴,另外在连接方面其实和 net/http 也有很多类似的方面。

fasthttp 暂未做深入研究,不过这种大量使用 复用内存 的思想确实使得其性能比 net/http 更好,甚至有大佬专门通过 pprof 比对了其性能,比较和 gin 的差异。

参考:
Go的fasthttp快的秘诀:简单事情做到极致

posted on 2024-03-18 10:59  进击的davis  阅读(18)  评论(0编辑  收藏  举报

导航