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

相关推荐
CAE虚拟与现实6 小时前
Redis如何保证存和读的过程中数据的一致性?
数据库·redis·缓存
Donk_6712 小时前
ELK+Redis架构搭建
redis·elk·架构
星轨zb13 小时前
JUC 到 Redis 分布式锁:一次关于高并发的性能压测实验
java·redis·分布式·jmeter
SuniaWang14 小时前
《Agentx专栏》03-架构设计:AgentX的六层架构是如何生长出来的
java·数据库·redis·docker·ai·架构
YL2004042616 小时前
【Redis基础篇】Redis常见命令
数据库·redis·缓存
Jing_jing_X17 小时前
DeepSeek 的上下文缓存是什么?它和程序里的 Redis 缓存一样吗?
redis·spring·缓存·ai
pixcarp18 小时前
Redis ZSet:底层设计与实践
数据库·redis·后端·学习·golang·web
shuair18 小时前
redis分布式锁
数据库·redis·分布式
不绝19119 小时前
AB包相关知识
开发语言·lua
TheWolfsfaith19 小时前
Redis服务键控建通知安装
数据库·redis·缓存