1. 首页>
  2. 技术文章>
  3. nginx中使用lua把请求存到redis

nginx中使用lua把请求存到redis

6/18/24 10:17:20 PM 浏览 900 评论 0

nginx lua redis

lua_code_cache on; 
 location /Api/Admin/XHS/WriteData {
    content_by_lua_block {
                local cjson = require "cjson"
                local redis = require "resty.redis"
                -- 连接到Redis
                local red = redis:new()
                red:set_timeout(1000)  -- 1秒超时
                local ok, err = red:connect("172.25.63.12", 6379)  
                if not ok then
                    ngx.say("连接Redis失败: ", err)
                    return
                end
                  -- 进行密码认证
                local res, auth_err = red:auth("密码")
                if not res then
                    ngx.say("Redis认证失败: ", auth_err)
                    return
                end
                
                -- 读取请求体数据
                ngx.req.read_body()
                local data = ngx.req.get_body_data()
                if not data then
                    ngx.say("请求中没有找到数据")
                    return
                end
                -- 在Redis中存储数据,你可以根据需要调整键名
                local redis_key = "some_key"
                local res, set_err = red:set(redis_key, data)
                if not res then
                    ngx.say("在Redis中存储数据失败: ", set_err)
                    return
                end
                -- 输出成功信息
                ngx.say("数据成功存储到Redis")
            }
 }


网友讨论