基於OpenResty部署nginx以及nginx+lua開發hello world課程筆記整理
阿新 • • 發佈:2020-11-05
中華石杉的億級流量電商詳情頁系統實戰(第二版):快取架構+高可用服務架構+微服務架構的課程筆記
用到的軟體資源
我們這裡玩兒nginx,全都會在nginx裡去寫lua指令碼,因為我們需要自定義一些特殊的業務邏輯
比如說,流量分發,自己用lua去寫分發的邏輯,在分發層nginx裡去寫的
再比如說,要用lua去寫多級快取架構存取的控制邏輯,在應用層nginx裡去寫的
後面還要做熱點資料的自動降級機制,也是用lua指令碼去寫降級機制的,在分發層nginx裡去寫的
因為我們要用nginx+lua去開發,所以會選擇用最流行的開源方案,就是用OpenResty
nginx+lua打包在一起,而且提供了包括redis客戶端,mysql客戶端,http客戶端在內的大量的元件
我們這一講是去部署應用層nginx,會採用OpenResty的方式去部署nginx,而且會帶著大家寫一個nginx+lua開發的一個hello world
1、部署第一個nginx,作為應用層nginx(192.168.31.187那個機器上)
(1)部署openresty
mkdir -p /usr/servers cd /usr/servers/ yum install -y readline-devel pcre-devel openssl-devel gcc wget http://openresty.org/download/ngx_openresty-1.7.7.2.tar.gz tar -xzvf ngx_openresty-1.7.7.2.tar.gz cd /usr/servers/ngx_openresty-1.7.7.2/ cd bundle/LuaJIT-2.1-20150120/ make clean && make && make install ln -sf luajit-2.1.0-alpha /usr/local/bin/luajit cd ../ wget https://github.com/FRiCKLE/ngx_cache_purge/archive/2.3.tar.gz tar -xvf 2.3.tar.gz wget https://github.com/yaoweibin/nginx_upstream_check_module/archive/v0.3.0.tar.gz tar -xvf v0.3.0.tar.gz cd /usr/servers/ngx_openresty-1.7.7.2 ./configure --prefix=/usr/servers --with-http_realip_module --with-pcre --with-luajit --add-module=./bundle/ngx_cache_purge-2.3/ --add-module=./bundle/nginx_upstream_check_module-0.3.0/ -j2 make && make install cd /usr/servers/ ll /usr/servers/luajit /usr/servers/lualib /usr/servers/nginx /usr/servers/nginx/sbin/nginx -V
啟動nginx: /usr/servers/nginx/sbin/nginx
(2)nginx+lua開發的hello world
vi /usr/servers/nginx/conf/nginx.conf
在http部分新增:
lua_package_path "/usr/servers/lualib/?.lua;;";
lua_package_cpath "/usr/servers/lualib/?.so;;";
/usr/servers/nginx/conf
下,建立一個lua.conf
server {
listen 80;
server_name _;
}
在nginx.conf
include lua.conf;
驗證配置是否正確:
/usr/servers/nginx/sbin/nginx -t
在lua.conf的server部分新增:
location /lua {
default_type 'text/html';
content_by_lua 'ngx.say("hello world")';
}
變成
server {
listen 80;
server_name _;
location /lua {
default_type 'text/html';
content_by_lua 'ngx.say("hello world")';
}
}
/usr/servers/nginx/sbin/nginx -t
重新nginx載入配置
/usr/servers/nginx/sbin/nginx -s reload
訪問http: http://127.0.0.1/lua
mkdir /usr/servers/nginx/conf/lua
vi /usr/servers/nginx/conf/lua/test.lua
寫入
ngx.say("hello world");
修改lua.conf
location /lua {
default_type 'text/html';
content_by_lua_file conf/lua/test.lua;
}
檢視異常日誌
tail -f /usr/servers/nginx/logs/error.log
(3)工程化的nginx+lua專案結構
專案工程結構
hello
hello.conf
lua
hello.lua
lualib
*.lua
*.so
放在/usr/hello目錄下
/usr/servers/nginx/conf/nginx.conf
worker_processes 2;
error_log logs/error.log;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type text/html;
lua_package_path "/usr/hello/lualib/?.lua;;";
lua_package_cpath "/usr/hello/lualib/?.so;;";
include /usr/hello/hello.conf;
}
/usr/hello/hello.conf
server {
listen 80;
server_name _;
location /lua {
default_type 'text/html';
lua_code_cache off;
content_by_lua_file /usr/example/lua/test.lua;
}
}