【openresty】- 研发笔记 - Lua脚本

127 阅读1分钟

背景

  • 使用openresty搭建website服务器,用户访问图片可以记录用户的访问记录

服务搭建

部署步骤

  • 前提: 服务搭建
  • 修改 my_server_block.conf文件;
    • 配置 匹配/lua_share/路径,响应 share_pic_visit.lua 文件逻辑.
    • 禁止 其他方式访问lua文件,避免源码文件被下载.
server {
  listen 0.0.0.0:8080;
  root /app;
  index index.htm index.html;
  location /lua_share/ {
    lua_code_cache off;
    content_by_lua_file /app/lua/share_pic_visit.lua;
  }
  location ~* .lua$ {
    deny all;
  }
}

# 备注: 修改了nginx配置后,需要重载nginx配置。 sudo docker exec openresty /opt/bitnami/openresty/nginx/sbin/nginx -s reload

目录结构示例

image.png

share_pic_visit.lua

-- openresty lua script

-- transpond request
local request_uri = ngx.var.request_uri
request_uri = string.gsub(request_uri, "/lua_share/", "/")
local res = ngx.location.capture(request_uri)
if res.status == 200 then
    ngx.print(res.body)
else
    ngx.log(ngx.ERR, "Failed to capture URI: ", request_uri)
end

-- get args
local args = ngx.req.get_uri_args()
local areaid, numid, timestamp = args.areaid, args.numid, args.timestamp
if not areaid or not numid or not timestamp then
    ngx.log(ngx.ERR, "Invalid areaid or numid or timestamp")
    return
end

-- connect redis function
local function connect_to_redis(ip, port, password)
    local redis = require("resty.redis")
    local rds = redis:new()
    rds:set_timeout(1000)

    -- attempt to connect to Redis
    local ok, err = rds:connect(ip, port)
    if not ok then
        ngx.log(ngx.ERR, "connect to redis error: ", err)
        return nil, err
    end

    -- authenticate with Redis
    local resp, err2 = rds:auth(password)
    if not resp then
        ngx.log(ngx.ERR, "failed to authenticate: ", err2)
        return nil, err2
    end

    return rds, nil
end

-- close redis function
local function close_redis(rds)
    if not rds then
        return
    end
    local ok, err = rds:close()
    if not ok then
        ngx.log(ngx.ERR, "close redis error: ", err)
    end
end

-- get redis config
local environment = "develop"
local RedisConfig = {
    production = { ip = "xxx.xxx.xxx.xx", port = 6380, password = "xxxxx" },
    test = { ip = "xxx.xxx.xxx.xx", port = 6380, password = "xxxxx" },
    develop = { ip = "xxx.xxx.xxx.xx", port = 6380, password = "xxxxx" }
}
local rdsConfig = RedisConfig[environment]

-- connect to redis
local rds, err = connect_to_redis(rdsConfig.ip, rdsConfig.port, rdsConfig.password)
if not rds then
    ngx.log(ngx.ERR, "connect to redis error: ", err)
    return close_redis(rds)
end

-- set redis key
local RedisKey_UserShareVisitPic = "user_share_visit_pic_%d_%d_%s"
local rdsKey = string.format(RedisKey_UserShareVisitPic, areaid, numid, timestamp)
local ok, err = rds:set(rdsKey, os.time() * 1000)
if not ok then
    ngx.log(ngx.ERR, "failed to incr: ", err)
    return close_redis(rds)
end
ok, err = rds:ttl(rdsKey)
if ok == -1 then
    rds:expire(rdsKey, 60 * 10)
end

close_redis(rds)