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

相关推荐
闻哥4 小时前
Redis 避坑指南:从命令到主从的全链路踩坑实录
java·数据库·redis·缓存·面试·springboot
小毅&Nora5 小时前
【后端】【Redis】② Redis事务管理全解:从“购物车结算“到“银行转账“,一文彻底掌握事务机制
数据库·redis·事务
假女吖☌6 小时前
限流算法-redis实现与java实现
java·redis·算法
what丶k6 小时前
深度解析Redis LRU与LFU算法:区别、实现与选型
java·redis·后端·缓存
菜宾6 小时前
java-redis面试题
java·开发语言·redis
a程序小傲10 小时前
得物Java面试被问:流批一体架构的实现和状态管理
java·开发语言·数据库·redis·缓存·面试·架构
小北方城市网12 小时前
Spring Cloud Gateway 生产级微内核架构设计与可插拔过滤器开发
java·大数据·linux·运维·spring boot·redis·分布式
是三好13 小时前
redis
数据库·redis·缓存
信也科技布道师13 小时前
基石Redis实例自动化调度之路
java·开发语言·redis·自动化