fasthttp源码分析,未完待续。。。

2021/5/2 20:30:29

本文主要是介绍fasthttp源码分析,未完待续。。。,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

fasthttp源码阅读

fasthttp本身无路由功能。

fasthttp传入函数而不是interface。 type RequestHandler func(ctx *RequestCtx)

fast http在返回时不得有对ctx及其成员的引用,并提供两种解决方案:

​ TimeoutHandler

​ TimeoutError

buffer tricks

  • So throw away nil checks for []byte buffers from you code.
String may be appended to []byte buffer with append
dst = append(dst, "foobar"...)

Because []byte to string conversion isn't free - it requires memory allocation and copy. Feel free wrapping returned []byte result into string() if you prefer working with strings instead of byte slices. But be aware that this has non-zero overhead

调用链路:

fasthttp.ListenAndServe()-->s.Serve()传递serveConn【serveConn中调用handler】到WorkerFunc。并执行WorkerPool.Start()

workerPool分析

workerPool struct: FILO顺序提供服务,理论上可保持CPU cache hot。

Start 函数:

chan struct{}不占用空间

WorkerChanPool--->sync.Pool ---New-->WorkerChan{上次使用时间,chan net.Conn}

对于WorkerChan的chan单核使用无缓冲【立即switches Server to WorkerFunc】,多核使用缓冲为1的chan:

goroutine:不断执行clean【间隔idle time,默认10s】

Clean函数:

根据最大闲置时间计算临界时间,二分查找【目标:wp.ready】到临界时间的位置然后记录要被淘汰的workerChan【用于停止】,更新ready为剩余需要保留的。

line:141 tmp[i].ch <- nil ?

Serve函数:

调用getCh,能拿到就把net.Conn【client】交给ch处理

getCh函数:

如果ready有则直接拿去用【ready--】

如果ready无:

  • 若workerCount小于MaxWorkersCount则从workerChanPoll【也是个sync.Poll】拿一个。
  • 否则返回nil

workerFunc函数:用于执行由外部传进来的实际的工作函数。在创建ch时陷入循环,从ch中读入net.Conn并处理。

MaxWorkersCount====> DefaultConcurrency = 256 * 1024

未完待续。。。。


copy函数:最多copy len(dst),返回拷贝数。



这篇关于fasthttp源码分析,未完待续。。。的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程