OpenResty 安装及lua-resty-redis

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

1. 下载openresty:

bash 复制代码
https://openresty.org/download/openresty-1.25.3.1.tar.gz

2. 编译安装

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

bash 复制代码
# 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和访问次数。

bash 复制代码
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 内容:

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 引用

bash 复制代码
location / {
    #root   html;
    #index  index.html index.htm;
    default_type text/html;
    access_by_lua_file lua/all_redis.lua;
}

相关文档地址: lua

相关推荐
却话巴山夜雨时i1 小时前
互联网大厂Java面试场景:Spring Boot、微服务与Redis实战解析
spring boot·redis·微服务·kafka·prometheus·java面试·电商场景
麒麟ZHAO2 小时前
鸿蒙flutter第三方库适配 - 文件对比工具
数据库·redis·flutter·华为·harmonyos
香蕉鼠片2 小时前
Redis
数据库·redis·缓存
小臭希2 小时前
Redis(NoSQL数据库,Linux-Ubuntu环境下)
数据库·redis·缓存
身如柳絮随风扬3 小时前
Redis中的哈希槽怎么理解
redis·哈希算法
未秃头的程序猿4 小时前
🚀 从“单机崩盘”到“集群稳如狗”:Redis 高可用避坑指南(保姆级实战)
redis·后端·面试
见山是山-见水是水5 小时前
鸿蒙flutter第三方库适配 - 汇率换算器
redis·flutter·华为·harmonyos
014-code5 小时前
Redis 删除缓存失败怎么办?重试、死信、补偿的工程化方案
数据库·redis·缓存
rannn_1116 小时前
【Redis|高级篇1】分布式缓存|持久化(RDB、AOF)、主从集群、哨兵、分片集群
java·redis·分布式·后端·缓存
PD我是你的真爱粉6 小时前
Redis 持久化、过期删除、淘汰策略与内存碎片全解析
java·redis·bootstrap