OpenResty HelloWorld

一、安装

以 CentOS 为例:

mkdir -p /opt

# download openresty
wget https://openresty.org/download/openresty-1.13.6.2.tar.gz

tar zxvf openresty-1.13.6.2.tar.gz
cd openresty-1.13.6.2

# configure
./configure --prefix=/opt/openresty -j4

make -j4 && make install

其中 源码包可以到 https://openresty.org/cn/download.html 该页面获取。
-j4表示使用4核。configure那一步还可以指定各种参数,使用 ./configure --help 查看更多的选项。

其它系统环境上安装可以参考 https://openresty.org/cn/installation.html 。

其实安装 OpenResty 和安装 Nginx 是类似的,因为 OpenResty 是基于 Nginx 开发的。

二、测试

查找nginx支持的3rd module:https://www.nginx.com/resources/wiki/modules/index.html

https://github.com/openresty/lua-nginx-module

openresty新手上路:https://openresty.org/cn/getting-started.html

1.测试1content_by_lua

修改/opt/openresty/nginx/conf/nginx.conf

worker_processes  1;
error_log logs/error.log;
events {
    worker_connections 1024;
}
http {
    server {
        listen 8080;
        location / {
            default_type text/html;
            content_by_lua_block {
                ngx.say("<p>hello, world</p>")
            }
        }
    }
}

其中content_by_lua便是 OpenResty 提供的指令,在官方文档可以搜索到:https://github.com/openresty/lua-nginx-module

/opt/openresty/nginx/sbin/nginx -s realod
curl http://localhost:8080/

2.测试2content_by_lua_file

修改/opt/openresty/nginx/conf/nginx.conf

 
worker_processes  1;
error_log logs/error.log;
events {
    worker_connections 1024;
}
http {
    server {
        listen 8080;
        location / {
            default_type text/html;
            content_by_lua {
                ngx.say("<p>hello, world</p>")
            }
        }
    }
}
mkdir nginx/conf/lua
vim nginx/conf/lua/hello.lua
ngx.say("hello lua")
/opt/openresty/nginx/sbin/nginx -s reload
curl http://localhost/

3、测试3lua_code_cache

为避免每次修改都需要重启Nginx,可在Nginx的server选项中配置lua_code_cache选项。

worker_processes  1;
error_log logs/error.log;
events {
    worker_connections 1024;
}
http {
    server {
        listen 8080;
        lua_code_cache off;
        location / {
            default_type text/html;
            content_by_lua {
                ngx.say("<p>hello, world</p>")
            }
        }
    }
}

提示说lua_code_cache关闭后影响性能。我们再次修改 nginx/conf/lua/hello.lua的代码,保存后就会生效,无需 reload server。

注意lua_code_cache off;是会引擎Nginx的性能的,在生产环境中是需要将其开启的。

三、小结

在OpenResty中开发是分为两步的,第一步是修改Nginx配置,第二步是使用Lua开发自己的脚本。

发布了524 篇原创文章 · 获赞 172 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/INGNIGHT/article/details/104823204