OpenResty 安装及lua-resty-redis

目的: 需要记录用户真实IP + 访问量

1. 下载openresty:

https://openresty.org/download/openresty-1.25.3.1.tar.gz

2. 编译安装

./configure --help | more 可以查看configure 可选参数

# 1、安装前置依赖
yum install -y readline-devel pcre pcre-devel openssl openssl-devel gcc curl GeoIP-devel perl

# 2、编译
##选择模块 ./configure --help
sudo ./configure --with-luajit --with-pcre --with-http_gzip_static_module --with-http_realip_module --with-http_geoip_module --with-http_ssl_module  --with-http_stub_status_module --without-lua_resty_redis

# 3、安装,默认安装在/usr/local/openresty 目录
sudo gmake
sudo gmake install

3. 安装 lua-resty-redis

说明:安装lua-resty-redis模块主要用于记录关键信息,例如:ip和访问次数。

git clone https://github.com/openresty/lua-resty-redis.git

sudo cp -r lua-resty-redis/lib/resty/* /usr/local/openresty/site/lualib/resty/

4. 创建lua 文件 ip_redis.lua 并引用

ip_redis.lua 内容:

local redis = require("resty.redis")
local red = redis:new()

-- 连接到 Redis
local ok, err = red:connect("192.168.1.2", 6379)
if not ok then
    ngx.log(ngx.ERR, "Failed to connect to Redis server: ", err)
    return
end

-- 身份验证
local res, err = red:auth("123456")
if not res then
    ngx.log(ngx.ERR, "Failed to authenticate: ", err)
    red:close()
    return
end

-- 选择数据库
local ok, err = red:select(1)
if not ok then
    ngx.log(ngx.ERR, "Failed to select database: ", err)
    red:close()
    return
end

-- 获取当前时间戳(秒)
local current_timestamp = ngx.now()

-- 设置 Redis 键,格式为 "ip:timestamp"
local key = ngx.var.remote_addr .. ":" .. math.floor(current_timestamp / 60)

-- 增加计数器
local res, err = red:incr(key)
if not res then
    ngx.log(ngx.ERR, "Failed to increment counter: ", err)
    red:close()
    return
end

-- 获取计数器的值
local count, err = red:get(key)
if not count then
    ngx.log(ngx.ERR, "Failed to get count: ", err)
    red:close()
    return
end

-- 关闭 Redis 连接
local ok, err = red:close()
if not ok then
    ngx.log(ngx.ERR, "Failed to close Redis connection: ", err)
    return
end

ngx.log(ngx.INFO, "IP ", ngx.var.remote_addr, " 访问了 ", count, " 次")

5. nginx.conf 引用

location / {
    #root   html;
    #index  index.html index.htm;
    default_type text/html;
    access_by_lua_file lua/all_redis.lua;
}

相关文档地址: lua

上一篇:Eclipse 安装 lombok 和配置


下一篇:基于Spring Boot的心灵治愈交流平台设计与实现