2.1.2 安装 LuaRocks(用于安装 Lua 模块)
bash
wget https://luarocks.org/releases/rocks-3.9.2.tar.gz
tar zxpf rocks-3.9.2.tar.gz
cd rocks-3.9.2
./configure prefix=/usr/local/openresty/luajit
make && sudo make install
function get_cached_content(key)
local cached = cache:get(key)
if cached then
return cached
end
return nil
end
function set_cached_content(key, value)
cache:set(key, value, 60) 缓存时间 60 秒
end
2.2.2 修改 Nginx 配置文件
在 `/etc/nginx/conf.d/cdn.conf` 中:
nginx
http {
upstream backend {
server your-origin-server.com;
}
lua_package_path /etc/nginx/lua/?.lua;;;
server {
listen 80;
location / {
access_by_lua_block {
local key = ngx.var.request_uri
local cached = get_cached_content(key)
if cached then
ngx.say(cached)
return
end
}
proxy_pass http://backend;
content_by_lua_block {
local key = ngx.var.request_uri
local res = ngx.fetch(http://backend .、ngx.var.request_uri)
if res.status == 200 then
set_cached_content(key, res.body)
ngx.say(res.body)
else
ngx.exit(500)
end
}
}
}
}