本文共 2672 字,大约阅读时间需要 8 分钟。
OpenResty 是一个高性能的 HTTP 和反向代理服务器,基于 Nginx 开发,支持 Lua 脚本处理。要实现简单的‘hello world’功能,可以通过以下两种方式实现:
编辑 nginx.conf 文件,找到相应的位置添加配置:
location / { default_type text/html; content_by_lua_block { ngx.say("hello world"); }} 重启 OpenResty 服务器即可完成配置。
如果希望将 Lua 代码独立出来,可以新建一个 Lua 文件(例如 my.lua),内容如下:
ngx.say("hello world"); 然后在 nginx.conf 中配置:
location / { default_type text/html; content_by_lua_file /home/luafile/my.lua;} OpenResty 提供了两种获取 URI 参数的方法:ngx.req.get_uri_args() 和 ngx.req.get_post_args(),分别用于获取 GET 请求和 POST 请求参数。
编写一个 Lua 脚本 geturl.lua:
local arg = ngx.req.get_uri_args()for k, v in pairs(arg) do ngx.say("[GET] key:", k, " v:", v)endlocal arg = ngx.req.get_post_args()for k, v in pairs(arg) do ngx.say("[POST] key:", k, " v:", v)end 在 nginx.conf 中配置:
location / { default_type text/html; content_by_lua_file /home/luafile/geturl.lua;} 编写一个 Lua 脚本 getheader.lua:
local headers = ngx.req.get_headers()for k, v in pairs(headers) do ngx.say("[header] name:", k, " v:", v)end 在 nginx.conf 中配置:
location / { default_type text/html; content_by_lua_file /home/luafile/getheader.lua;} 编写一个 Lua 脚本 getbody.lua:
local data = ngx.req.get_body_data()ngx.say(data)
在 nginx.conf 中配置:
location / { default_type text/html; content_by_lua_file /home/luafile/getbody.lua;} 编写一个 Lua 脚本 redis.lua:
local redis = require "resty.redis"local red = redis:new()red:set_timeout(1000) -- 设置超时为 1 秒local ok, err = red:connect("192.168.222.134", 6379)if not ok then ngx.say("failed to connect: ", err) returnend-- Redis 认证local count, err = red:get_reused_times()if 0 == count then local ok, err = red:auth("123456") if not ok then ngx.say("failed to auth: ", err) return endelseif err then ngx.say("failed to get reused times: ", err) returnend-- 设置值local ok, err = red:set("blogger", "very handsome")if not ok then ngx.say("failed to set it: ", err) returnendngx.say("set result: ", ok)-- 设置连接池大小local ok, err = red:set_keepalive(10000, 100)if not ok then ngx.say("failed to set keepalive: ", err) returnend 在 nginx.conf 中配置:
location / { default_type text/html; content_by_lua_file /home/luafile/redis.lua;} 版本兼容性:OpenResty 的 content_by_lua 命令在 1.9.3.1 及以下版本为 content_by_lua_block,在 1.9.3.2 及以上版本改为 content_by_lua。可以通过 nginx -V 查看版本号。
参数处理:在处理 POST 请求参数时,记得先调用 ngx.req.read_body() 或启用 lua_need_request_body 选项,否则可能无法获取到请求体数据。
性能优化:对于高并发场景,可以通过调整 Redis 连接池大小(如 set_keepalive)来优化性能。
转载地址:http://acpfk.baihongyu.com/