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

相关推荐
甜可儿30 分钟前
redis序列化设置
数据库·redis
千层冷面2 小时前
Redis除了做缓存还能做什么?
数据库·redis·缓存
zr想努力3 小时前
Lua的table类型的增删改查操作
java·开发语言·lua
码有余悸3 小时前
Redis:高性能的键值存储系统
数据库·redis·缓存
老朋友此林10 小时前
浅析 Redis 分片集群 Cluster 原理、手动搭建、动态伸缩集群、故障转移
java·数据库·redis
因兹菜12 小时前
[LeetCode]day29 232.用栈实现队列
redis·算法·leetcode
guihong00414 小时前
深入理解 Redis 设计与集群管理
数据库·redis·缓存
alenliu062114 小时前
跟着 Lua 5.1 官方参考文档学习 Lua (8)
lua
笨鸟先飞的橘猫14 小时前
lua学习(一)
开发语言·学习·lua
IT_狂奔者15 小时前
Redis Lua Script 溢出漏洞(CVE-2024-31449)
数据库·redis·lua