9

OpenResty 101

 5 years ago
source link: https://www.tuicool.com/articles/RR3q6zJ
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

本文是 OpenResty 的初学者指南,提供一些资料的汇总。

UB7rumA.jpg!web

OpenResty

初学者在刚开始学习 OpenResty 的时候,最好对 Nginx 有一定的了解,推荐阅读 OpenResty 作者 agentzh 撰写的 Nginx 教程,有 中文版英文版

一旦对 Nginx 有了基本的认知,那么可以读十遍 lua-nginx-module 的 官方文档 ,同时 iresty 上还提供了一份 中文文档 ,文档中很多细节都值得牢记。

比如在描述 ngx.print 的时候,文档中提到:「This is an asynchronous call and will return immediately without waiting for all the data to be written into the system send buffer. To run in synchronous mode, call ngx.flush(true) after calling ngx.print.」,看上去很简单,无非是说 ngx.print 是异步的,不过如果你忽视了这一点,那么很可能会掉坑里:

我见过有人在热代码里执行 ngx.print,结果导致卡顿,究其原因,正是因为 ngx.print 是异步的,调用后直接返回,正确的做法是在适当的时候执行 ngx.flush(true)。

此外,在描述 ngx.say 的时候,文档中提到:「Just as ngx.print but also emit a trailing newline.」,看上去很简单,无非是说 ngx.say 比 ngx.print 多了一个新行,不过如果你忽视了这一点,那么很可能会掉坑里:

我见过有人输出了 Content-Length 响应头后,接着用 ngx.say 输出相应体,结果报错。究其原因,正是因为 ngx.say 多了一个新行,导致 Content-Length 不匹配。

除了文档,还有一些开源的电子书值得推荐,比如:

理论知识学习的差不多了之后,可以泡泡讨论组( 中文英文 ),把帖子从头到尾捋一遍,倒不用非得捋得多仔细,更重要的是看看别人是如何解决问题的。

比如很多性能问题都是用火焰图解决的,其又分为 On-CPU 和 Off-CPU,如何选择?

如果瓶颈是 CPU 则使用 On-CPU 火焰图,如果瓶颈是 IO 或锁则使用 Off-CPU 火焰图。如果无法确定,那么可以通过压测工具来确定:通过压测工具看看能否让 CPU 使用率趋于饱和,如果能那么使用 On-CPU 火焰图,如果不管怎么压,CPU 使用率始终上不来,那么多半说明程序被 IO 或锁卡住了,此时适合使用 Off-CPU 火焰图。如果还是确认不了,那么不妨 On-CPU 火焰图和 Off-CPU 火焰图都搞搞,正常情况下它们的差异会比较大,如果两张火焰图长得差不多,那么通常认为 CPU 被其它进程抢占了。

当你实际用 OpenResty 写项目的时候,最好站在巨人的肩膀上,多使用一些成熟的开源组件,每次有什么需求时记得先在 awesome-resty 上找找,Github 上 lua-resty-* 相关的项目最好也都留意一下,特别是如下几个公司的账户: upyunkongcloudflare ,尤其是 upyun,作为国内技术流公司,对 OpenResty 社区 贡献 良多,此外,再推荐几个个人账户: timebugdoujiang24bungleledgetechthibaultcha 等等。

不多说了,撸起袖子干吧。

jYfAnqq.png!web


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK