OpenResty 之安装测试

1,658 阅读3分钟

OpenResty 之前一直比较关注,后来在工作中也有幸简单的使用过,稳定性和易用性给了我深刻的印象。

有时回想起曾经接触过很多有趣的项目和技术,但大部分都浮于表面,很多都是给自己找借口, 想之后有时间再深入研究分享下,却由于自己的懒惰大部分都不了了之。

要不再给我一次机会, 让我们从头开始一起加油?

mac 系统快速安装

brew install openresty/brew/openresty

resty 命令

resty 命令快速测试

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

output:
hello world

resty命令背后的操作

#查看 openstry 进程
ps -ef|grep openrestry

output: 

/usr/local/Cellar/openresty/1.15.8.2/nginx/sbin/nginx 
-p /tmp/resty_MnSJsgRCEI/ 
-c conf/nginx.conf

我们看到有个 nginx 启动进程, 其实内部执行了 nginx 命令, -p 指定了一个新的临时目录作为前缀路径. 当进程执行完毕后自动销毁

我们在代码中加入 sleep 查看临时目录里面存了些什么

resty -e "os.execute('sleep '..12)  ngx.say('hello world')"

编写项目

nginx.conf 配置中加入 lua 代码

events {
    worker_connections 1024;
}

http {
    server {
        listen 8080;
        location /test {
            content_by_lua '
                ngx.say("hello, world")
            ';
        }
    }
}

我们使用 openresty 命令启动项目

# 当前目录作为前缀工作目录启动
openresty -p `pwd` -c conf/nginx.conf
# 重启
openresty -s reload

我们可以使用 openresty -h 具体的参数含义

-p 的含义可简单理解为指定项目的工作目录, -c 指定 nginx 配置.

curl 请求测试

curl -i http://127.0.0.1:8080/test

HTTP/1.1 200 OK
Server: openresty/1.15.8.2
Date: Sun, 10 Nov 2019 14:53:14 GMT
Content-Type: text/plain
Transfer-Encoding: chunked
Connection: keep-alive

hello, world

content_by_lua_file

上面例子我们的 lua 代码和 nginx 配置耦合混用在一起, 这不是一个好的习惯.

下面我们通过调用 lua 脚本文件的方式来实现简单输出

nginx.conf

location /test {
    content_by_lua_file lua/test.lua;
}

我们看到 content_by_lua_file 指定了相对目录下的 lua/test.lua 文件, 那具体 lua 绝对目录应该建在什么地方呢?

我们可以通过 restydoc 命令快速查看下 content_by_lua_file 的解释:

通过上图我们看到了这个参数的语法和作用域, 还记得上面我们在启动服务的时候指定了 -p 参数, 工作目录前缀参数, 他会从这个目录下去找 lua目录下的 test.lua

如果我们想换成其他路径可以使用绝对路径

location /test {
    content_by_lua_file /Users/xxxx/Desktop/kong/lua/test.lua;
}

继续看上图发现 content_by_lua_file 还支持第二个参数, 也可以这样使用

location /test {
    lua_code_cache off;
    content_by_lua_file test.lua /Users/wenba/Desktop/kong/lua;
}

如何让你的 lua 代码即时生效

我们发现每次修改完 lua 代码,都需要重启 openresty, 如果我们在开发环境中, 如何充分发挥出脚本的开发高效率呢?

我们可以使用 lua_code_cache 指令, 将它设置为关闭即可

location /test {
    lua_code_cache off;
    content_by_lua_file lua/test.lua;
}

附录

自学成菜-流水账学习法lua入门

自学成菜-openrestry(1)

欢迎大家关注我的公众号: 【呆呆熊的技术路】