openresty笔记

hello world

2019-06-15  本文已影响0人  赵帅_a4fe

hello world 编写

$ resty -e "ngx.say('hello world')"
hello world

一行代码,非常的简洁。
openresty是基于nginx的,为什么我们看不到nginx的影子 ?
我们修改下代码,执行完打印以后,休眠一段时间,再退出程序

resty -e "ngx.say('hello world'); ngx.sleep(10)" &

我们看下nginx的进程

$ ps -ef | grep nginx
501 25468 25462   0  7:24 下午 ttys000    0:00.01 /usr/local/Cellar/openresty/''1.13.6.2/nginx/sbin/nginx -p /tmp/resty_AfNwigQVOB/ -c conf/nginx.conf

可以看到 hello world 程序执行,openresty启动了一个nginx服务。

openresty 安装

推荐优先使用 yum、apt-get、brew 这类包管理,来安装openresty

brew tap openresty/brew
brew install openresty

这里有两个问题

安装完成以后,我们可以看下openresty的版本信息

$ openresty -V
nginx version: openresty/1.13.6.2
built by clang 10.0.0 (clang-1000.10.44.4)
built with OpenSSL 1.1.0h  27 Mar 2018
TLS SNI support enabled
configure arguments: --prefix=/usr/local/Cellar/openresty/1.13.6.2/nginx ...

hello world web版

mkdir geektime
cd geektime
mkdir logs/ conf/

events {
    worker_connections 1024;
}
http {
    server {
        listen 8080;
        location / {
            content_by_lua '
                ngx.say("hello, world")
            ';
        }
    }
}
openresty -p `pwd` -c conf/nginx.conf
$ curl -i 127.0.0.1:8080
HTTP/1.1 200 OK
Server: openresty/1.13.6.2
Content-Type: text/plain
Transfer-Encoding: chunked
Connection: keep-alive

hello, world

至此,web版的hello world 就完成了

抽离lua代码

$ mkdir lua
$ cat lua/hello.lua
ngx.say("hello, world")
pid logs/nginx.pid;
events {
    worker_connections 1024;
}

http {
    server {
        listen 8080;
        location / {
            content_by_lua_file lua/hello.lua;
            }
        }
    }
}

content_by_lua_file lua/hello.lua;写的是相对路径,openresty是如何找到对应的文件的呢?
openresty 启动时会有-p PATH ,使用这个路径作为前缀,然后拼接上相对路径,从而构成了一个绝对路径定位到文件
另外,openresty 提供了lua_package_path命令来定义lua模块的查找路径,比如$prefix/lua/?.lua;;
$prefix为-p Path,lua/?.lua表示lua目录下所有的以.lua结尾的文件,;;代表内置的代码搜索路径
项目中一般我们都会定义lua代码的包路径
lua代码会在第一个请求时被加载,并且默认缓存起来,每次修改lua代码以后,需要重新加载才能生效,在开发调试过程中,一般将lua_code_cache关闭,不缓存从而每次都加载最新的代码,但线上欢迎一定要打开缓存,否则会非常影响性能。

$ sudo kill -HUP `cat logs/nginx.pid`
上一篇下一篇

猜你喜欢

热点阅读