OpenResty(4):OpenResty快速入门
发布日期:2025-04-29 04:54:17 浏览次数:16 分类:精选文章

本文共 2672 字,大约阅读时间需要 8 分钟。

OpenResty + Lua 实用指南

1. 简单的‘hello world’示例

OpenResty 是一个高性能的 HTTP 和反向代理服务器,基于 Nginx 开发,支持 Lua 脚本处理。要实现简单的‘hello world’功能,可以通过以下两种方式实现:

方法一:直接在 nginx.conf 中使用 content_by_lua_block

编辑 nginx.conf 文件,找到相应的位置添加配置:

location / {    default_type text/html;    content_by_lua_block {        ngx.say("hello world");    }}

重启 OpenResty 服务器即可完成配置。

方法二:使用 content_by_lua_file 加载外部 Lua 文件

如果希望将 Lua 代码独立出来,可以新建一个 Lua 文件(例如 my.lua),内容如下:

ngx.say("hello world");

然后在 nginx.conf 中配置:

location / {    default_type text/html;    content_by_lua_file /home/luafile/my.lua;}

2. 获取 HTTP 请求信息

2.1 获取 URI 参数

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;}

2.2 获取 Header

编写一个 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;}

2.3 获取 Request Body

编写一个 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;}

3. 与 Redis 交互

Redis 连接与操作

编写一个 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)来优化性能。

  • 上一篇:OpenResty(5):Openresty 模板渲染
    下一篇:OpenResty(3):OpenResty快速入门之安装lua

    发表评论

    最新留言

    逛到本站,mark一下
    [***.202.152.39]2026年05月23日 07时01分33秒