在当前的互联网服务架构中,API网关作为流量入口承担着越来越重要的角色。Rocky Linux 8.6作为RHEL生态的稳定分支,配合Nginx的高性能特性,再结合Lua脚本的灵活性,能够构建出既稳定又具备高度定制能力的API网关解决方案。这套组合特别适合需要处理高并发请求、同时又要求灵活业务逻辑的场景。
我最近在一个日请求量超过500万的电商项目中实践了这套方案,通过合理的配置和调优,最终将平均响应时间从78ms降低到32ms,错误率从1.2%降至0.3%。下面就把这套经过实战检验的配置方案分享给大家。
首先确保你的Rocky Linux 8.6系统是最新状态:
bash复制sudo dnf update -y
sudo dnf install -y epel-release
对于API网关场景,我们需要调整一些内核参数。编辑/etc/sysctl.conf文件,添加以下配置:
conf复制net.core.somaxconn = 32768
net.ipv4.tcp_max_syn_backlog = 8192
net.ipv4.tcp_tw_reuse = 1
net.ipv4.ip_local_port_range = 1024 65000
fs.file-max = 2097152
执行sysctl -p使配置生效。这些参数调整了系统级的连接数限制和TCP协议栈行为,为高并发场景做好准备。
我们选择OpenResty作为Nginx的增强版本,它内置了LuaJIT支持:
bash复制sudo dnf install -y yum-utils
sudo yum-config-manager --add-repo https://openresty.org/package/centos/openresty.repo
sudo dnf install -y openresty openresty-resty
验证安装是否成功:
bash复制openresty -v
resty -e 'print("Lua运行正常")'
编辑/usr/local/openresty/nginx/conf/nginx.conf,在http块中添加以下关键配置:
nginx复制http {
lua_package_path '/usr/local/openresty/lualib/?.lua;;';
lua_shared_dict api_cache 128m;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
keepalive_requests 10000;
client_max_body_size 20m;
client_body_buffer_size 128k;
client_header_buffer_size 4k;
large_client_header_buffers 4 16k;
gzip on;
gzip_min_length 1k;
gzip_comp_level 4;
gzip_types text/plain application/json;
}
这些配置中:
lua_shared_dict创建了Lua共享内存区域,用于缓存API路由等数据在main上下文中调整worker配置:
nginx复制worker_processes auto;
worker_rlimit_nofile 65535;
events {
worker_connections 16384;
multi_accept on;
use epoll;
}
这里有几个关键点:
worker_processes设为auto会自动匹配CPU核心数worker_rlimit_nofile需要与系统级的fs.file-max匹配use epoll在Linux系统上是必须的,这是最高效的事件模型在/usr/local/openresty/nginx/conf/lua/目录下创建auth.lua:
lua复制local _M = {}
function _M.check_api_key()
local args = ngx.req.get_uri_args()
local api_key = args["api_key"]
if not api_key then
ngx.status = ngx.HTTP_UNAUTHORIZED
ngx.say('{"error": "API key missing"}')
return ngx.exit(ngx.HTTP_UNAUTHORIZED)
end
-- 这里可以添加实际的key验证逻辑
-- 例如查询redis或数据库
end
return _M
然后在Nginx配置中使用:
nginx复制location /api {
access_by_lua_block {
local auth = require "lua.auth"
auth.check_api_key()
}
proxy_pass http://backend;
}
lua复制local ngx = ngx
local string = string
local table = table
lua复制local ffi = require "ffi"
local cjson = require "cjson.safe"
lua复制local dict = ngx.shared.api_cache
local value, flags = dict:get(key)
if not value then
value = get_value_from_db()
dict:set(key, value, 60) -- 缓存60秒
end
使用Lua实现动态upstream选择:
lua复制local balancer = require "ngx.balancer"
local host = {"10.0.0.1", "10.0.0.2", "10.0.0.3"}
local ok, err = balancer.set_current_peer(host[math.random(#host)])
if not ok then
ngx.log(ngx.ERR, "failed to set peer: ", err)
return ngx.exit(500)
end
配置结构化日志:
nginx复制log_format json_log escape=json
'{"time":"$time_iso8601",'
'"host":"$host",'
'"status":"$status",'
'"request_time":"$request_time",'
'"upstream_time":"$upstream_response_time"}';
access_log /var/log/nginx/access.log json_log;
添加Prometheus监控:
lua复制location /metrics {
content_by_lua_block {
local metric = require "resty.prometheus"
local prometheus = metric.new()
prometheus:counter("api_requests_total", "Total API requests")
:inc(1, {ngx.var.host, ngx.var.status})
ngx.print(prometheus:metric_data())
}
}
使用wrk进行基准测试:
bash复制wrk -t12 -c400 -d30s http://localhost/api/v1/products
优化前后的关键指标对比:
| 指标 | 优化前 | 优化后 | 提升 |
|---|---|---|---|
| QPS | 2,300 | 8,700 | 278% |
| 平均延迟 | 78ms | 32ms | 59% |
| P99延迟 | 420ms | 150ms | 64% |
| 错误率 | 1.2% | 0.3% | 75% |
当Lua脚本出错时,检查错误日志:
bash复制tail -f /usr/local/openresty/nginx/logs/error.log
常见错误包括:
使用systemtap进行深度分析:
bash复制stap -e 'probe process("/usr/local/openresty/nginx/sbin/nginx").function("*") { println(ppfunc()) }'
常见瓶颈点:
如果遇到连接数不足的问题:
ulimit -n值worker_connections与worker_rlimit_nofile的匹配关系ss -s输出的TCP状态统计灰度发布策略:
灾备方案:
nginx复制upstream backend {
server 10.0.0.1:8080 max_fails=3 fail_timeout=30s;
server 10.0.0.2:8080 backup;
}
配置管理:
这套配置在实际项目中已经稳定运行了6个月,期间经历了多次大促活动的考验。关键是要根据实际业务特点调整参数,特别是缓存时间和连接池大小。建议先在小流量环境测试,逐步优化到最佳状态。