OpenResty -- Nginx + Lua 访问 Redis
摘要
- 本文介绍如何通过 OpenResty 实现 Nginx + Lua 访问 Redis
- 本文基于
redis-7.4.7 - Redis官网:https://redis.io/
- OpenResty官网:https://openresty.org/
OpenResty 简介
-
OpenResty® 是一个基于 Nginx 与 Lua 的高性能 Web 平台,其内部集成了大量精良的 Lua 库、第三方模块以及大多数的依赖项。用于方便地搭建能够处理超高并发、扩展性极高的动态 Web 应用、Web 服务和动态网关。
-
OpenResty® 通过汇聚各种设计精良的 Nginx 模块(主要由 OpenResty 团队自主开发),从而将 Nginx 有效地变成一个强大的通用 Web 应用平台。这样,Web 开发人员和系统工程师可以使用 Lua 脚本语言调动 Nginx 支持的各种 C 以及 Lua 模块,快速构造出足以胜任 10K 乃至 1000K 以上单机并发连接的高性能 Web 应用系统。
-
OpenResty® 的目标是让你的Web服务直接跑在 Nginx 服务内部,充分利用 Nginx 的非阻塞 I/O 模型,不仅仅对 HTTP 客户端请求,甚至于对远程后端诸如 MySQL、PostgreSQL、Memcached 以及 Redis 等都进行一致的高性能响应。
OpenResty 安装
MacOS
-
MacOS 版本:
15.7.3 -
通过 Homebrew 安装
1 | brew tap openresty/brew |
-
安装时报错
1 | checking for GeoIP library ... not found |
-
解决办法
1 | brew edit openresty/brew/openresty |
-
OpenResty 命令说明
1 | openresty -h |
| 参数 | 完整写法 | 中文含义 | 典型使用场景 | 示例 |
|---|---|---|---|---|
-h / -? |
openresty -h |
显示帮助信息并退出 | 快速查看可用参数 | openresty -h |
-v |
openresty -v |
显示版本号 | 确认运行版本 | openresty -v |
-V |
openresty -V |
显示版本号 + 编译参数 | 排查模块、编译选项、依赖 | openresty -V |
-t |
openresty -t |
校验配置文件合法性并退出 | 修改配置后验证语法 | openresty -t |
-T |
openresty -T |
校验配置并打印完整配置内容 | 排查 include 文件、调试配置加载顺序 | openresty -T |
-q |
openresty -t -q |
测试配置时只输出错误信息 | CI / 自动化脚本 | openresty -t -q |
-s |
openresty -s reload |
向 master 进程发送控制信号 | 服务管理(重载、停止等) | openresty -s reload |
stop |
立即停止服务(强制) | 紧急停服 | openresty -s stop |
|
quit |
优雅停止服务(处理完请求后退出) | 平滑下线 | openresty -s quit |
|
reload |
平滑重载配置 | 发布配置变更 | openresty -s reload |
|
reopen |
重新打开日志文件 | 日志切割后使用 | openresty -s reopen |
|
-p |
openresty -p /path |
指定运行前缀目录(prefix) | 多实例部署、定制目录结构 | openresty -p /opt/openresty |
-e |
openresty -e file |
指定错误日志路径 | 临时调试错误日志 | openresty -e /tmp/error.log |
-c |
openresty -c file |
指定配置文件路径 | 使用非默认配置启动 | openresty -c ./nginx.conf |
-g |
openresty -g "daemon off;" |
设置全局指令(覆盖配置文件) | 容器化 / 临时调试 | openresty -g "daemon off;" |
-
安装后的目录
1 | # 安装目录 |
示例
-
vim test-nginx.conf
1 | worker_processes 1; |
-
启动
1 | openresty -p `pwd` -c ./test-nginx.conf |
-
访问
1 | curl http://127.0.0.1:8080 |
Nginx + Lua + Redis 限流完整示例
限流设计说明
-
限流规则
1 | 维度:客户端 IP |
-
Redis Key 设计
1 | rate:{client_ip}:{minute_timestamp} |
-
vim redis-nginx.conf
1 | worker_processes 1; |
-
启动
1 | openresty -p `pwd` -c ./redis-nginx.conf |
-
访问
1 | for i in {1..15}; do |