1. OpenResty概述与环境规划
OpenResty是一个基于Nginx与Lua的高性能Web平台,由章亦春开发。它将Nginx核心、LuaJIT、许多精心编写的Lua库和大量第三方Nginx模块组合在一起,用于搭建高性能动态Web应用、Web服务和动态网关。更多学习教程www.fgedu.net.cn
1.1 OpenResty版本说明
OpenResty目前主要版本为1.25,本教程以OpenResty 1.25为例进行详细讲解。
$ openresty -v
nginx version: openresty/1.25.3.1
# 查看编译参数
$ openresty -V
nginx version: openresty/1.25.3.1
built by gcc 8.5.0 20210514 (Red Hat 8.5.0-20) (GCC)
built with OpenSSL 3.0.7 1 Nov 2022
TLS SNI support enabled
configure arguments: –prefix=/usr/local/openresty/nginx –with-cc-opt=-O2 –add-module=../ngx_devel_kit-0.3.3 –add-module=../lua-nginx-module-0.10.26 –add-module=../lua-upstream-nginx-module-0.07
# 检查配置语法
$ openresty -t
nginx: the configuration file /usr/local/openresty/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/openresty/nginx/conf/nginx.conf test is successful
1.2 环境规划
本次安装环境规划如下:
IP地址:192.168.1.51
HTTP端口:80
HTTPS端口:443
安装目录:/usr/local/openresty
日志目录:/var/log/openresty
配置目录:/usr/local/openresty/nginx/conf
Lua目录:/usr/local/openresty/lualib
OpenResty版本:1.25.3.1
Nginx版本:1.25.3
LuaJIT版本:2.1
1.3 OpenResty核心特性
1. 高性能:基于Nginx和LuaJIT,性能优异
2. 动态编程:支持Lua脚本动态处理请求
3. 非阻塞IO:所有网络操作都是非阻塞的
4. 协程:Lua协程实现高并发处理
5. 丰富模块:内置大量实用模块
6. API网关:适合构建API网关和WAF
7. 缓存:支持共享内存和Lua缓存
8. 数据库连接:支持MySQL、Redis等连接池
2. 硬件环境要求与检查
在安装OpenResty之前,需要对服务器硬件环境进行全面检查。学习交流加群风哥微信: itpux-com
2.1 最低硬件要求
CPU:1核心
内存:512MB
磁盘:5GB
推荐配置(生产环境):
CPU:4核心以上
内存:8GB以上
磁盘:50GB以上
高并发配置:
CPU:8核心以上
内存:16GB以上
磁盘:100GB以上(SSD)
2.2 系统环境检查
# cat /etc/redhat-release
Red Hat Enterprise Linux release 8.8 (Ootpa)
# 检查内核版本
# uname -r
4.18.0-477.27.1.el8_8.x86_64
# 检查内存信息
# free -h
total used free shared buff/cache available
Mem: 15Gi 1.0Gi 13Gi 256Mi 1.0Gi 14Gi
Swap: 7Gi 0B 7Gi
# 检查磁盘空间
# df -h
文件系统 容量 已用 可用 已用% 挂载点
/dev/mapper/vg_system-lv_root 100G 5.0G 95G 5% /
/dev/mapper/vg_data-lv_data 500G 50G 450G 10% /data
2.3 依赖包检查
# rpm -qa | grep -E “gcc|pcre|zlib|openssl|readline”
gcc-8.5.0-20.el8.x86_64
pcre-devel-8.45-1.el8.x86_64
zlib-devel-1.2.11-25.el8.x86_64
openssl-devel-3.0.7-24.el8.x86_64
readline-devel-8.0-4.el8.x86_64
# 安装依赖包
# yum install -y gcc pcre pcre-devel zlib zlib-devel openssl openssl-devel readline readline-devel perl
# 输出示例:
Last metadata expiration check: 0:00:00 ago on Sat Apr 4 10:00:00 2026.
Dependencies resolved.
Complete!
3. OpenResty安装步骤
本节详细介绍OpenResty 1.25的安装过程。学习交流加群风哥QQ113257174
3.1 创建用户和目录
# groupadd -g 81 openresty
# useradd -u 81 -g openresty -s /sbin/nologin -M openresty
# 创建目录
# mkdir -p /usr/local/openresty
# mkdir -p /var/log/openresty
# mkdir -p /data/openresty/{html,ssl,lua}
# 设置目录权限
# chown -R openresty:openresty /var/log/openresty
# chown -R openresty:openresty /data/openresty
3.2 添加OpenResty仓库
# yum install -y yum-utils
# yum-config-manager –add-repo https://openresty.org/package/centos/openresty.repo
# 输出示例:
Adding repo from: https://openresty.org/package/centos/openresty.repo
# 查看可用版本
# yum list openresty –showduplicates
# 输出示例:
openresty.x86_64 1.25.3.1-1.el8 openresty
openresty.x86_64 1.21.4.3-1.el8 openresty
3.3 安装OpenResty
# yum install -y openresty
# 输出示例:
Installed:
openresty-1.25.3.1-1.el8.x86_64
Complete!
# 验证安装
$ openresty -v
nginx version: openresty/1.25.3.1
# 查看安装目录
$ ls -la /usr/local/openresty/
# 输出示例:
总用量 0
drwxr-xr-x. 2 root root 6 4月 4 10:00 bin
drwxr-xr-x. 5 root root 107 4月 4 10:00 luajit
drwxr-xr-x. 6 root root 59 4月 4 10:00 lualib
drwxr-xr-x. 2 root root 6 4月 4 10:64 nginx
3.4 配置环境变量
# vi /etc/profile.d/openresty.sh
export PATH=/usr/local/openresty/bin:$PATH
export PATH=/usr/local/openresty/nginx/sbin:$PATH
# 使配置生效
# source /etc/profile.d/openresty.sh
# 验证环境变量
$ which openresty
/usr/local/openresty/bin/openresty
3.5 创建systemd服务
# vi /usr/lib/systemd/system/openresty.service
[Unit]
Description=The OpenResty Application Platform
After=network.target remote-fs.target nss-lookup.target
Wants=network-online.target
[Service]
Type=forking
PIDFile=/usr/local/openresty/nginx/logs/nginx.pid
ExecStartPre=/usr/local/openresty/nginx/sbin/nginx -t
ExecStart=/usr/local/openresty/nginx/sbin/nginx
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true
[Install]
WantedBy=multi-user.target
# 重载systemd
# systemctl daemon-reload
# 启动OpenResty
# systemctl start openresty
# 设置开机自启
# systemctl enable openresty
# 检查状态
# systemctl status openresty
# 输出示例:
● openresty.service – The OpenResty Application Platform
Loaded: loaded (/usr/lib/systemd/system/openresty.service; enabled; vendor preset: disabled)
Active: active (running) since Sat 2026-04-04 10:00:00 CST; 1s ago
Main PID: 12345 (nginx)
Tasks: 3 (limit: 49134)
Memory: 2.5M
CGroup: /system.slice/openresty.service
├─12345 nginx: master process
├─12346 nginx: worker process
└─12347 nginx: worker process
3.6 配置防火墙
# firewall-cmd –permanent –add-service=http
success
# firewall-cmd –permanent –add-service=https
success
# firewall-cmd –reload
success
# 验证安装
$ curl -I http://192.168.1.51
# 输出示例:
HTTP/1.1 200 OK
Server: openresty/1.25.3.1
Date: Sat, 04 Apr 2026 02:00:00 GMT
Content-Type: text/html
Content-Length: 615
Connection: keep-alive
4. OpenResty参数配置
OpenResty参数配置是性能优化的关键步骤,直接影响系统性能。更多学习教程公众号风哥教程itpux_com
4.1 主配置文件
# vi /usr/local/openresty/nginx/conf/nginx.conf
user openresty;
worker_processes auto;
worker_rlimit_nofile 65535;
error_log /var/log/openresty/error.log notice;
pid /usr/local/openresty/nginx/logs/nginx.pid;
events {
worker_connections 65535;
use epoll;
multi_accept on;
}
http {
include mime.types;
default_type application/octet-stream;
log_format main ‘$remote_addr – $remote_user [$time_local] “$request” ‘
‘$status $body_bytes_sent “$http_referer” ‘
‘”$http_user_agent” “$http_x_forwarded_for”‘;
access_log /var/log/openresty/access.log main;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_types text/plain text/css application/json application/javascript;
# Lua模块路径
lua_package_path “/usr/local/openresty/lualib/?.lua;/data/openresty/lua/?.lua;;”;
lua_package_cpath “/usr/local/openresty/lualib/?.so;;”;
# Lua共享内存
lua_shared_dict cache 100m;
lua_shared_dict limit 10m;
lua_shared_dict status 1m;
include conf.d/*.conf;
}
# 检查配置
$ openresty -t
nginx: the configuration file /usr/local/openresty/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/openresty/nginx/conf/nginx.conf test is successful
# 重载配置
$ openresty -s reload
4.2 Lua配置优化
# vi /usr/local/openresty/nginx/conf/nginx.conf
http {
# Lua模块路径
lua_package_path “/usr/local/openresty/lualib/?.lua;/data/openresty/lua/?.lua;;”;
lua_package_cpath “/usr/local/openresty/lualib/?.so;;”;
# Lua共享内存
lua_shared_dict cache 100m;
lua_shared_dict limit 10m;
lua_shared_dict status 1m;
# Lua代码缓存(生产环境开启)
lua_code_cache on;
# Lua最大请求体大小
lua_max_pending_timers 1024;
lua_max_running_timers 256;
# 初始化Lua脚本
init_by_lua_block {
require “resty.core”
local cache = ngx.shared.cache
cache:set(“version”, “1.0.0”)
}
# Worker初始化
init_worker_by_lua_block {
local timer = require “resty.timer”
timer.run()
}
}
5. Lua开发
OpenResty的核心优势是支持Lua脚本开发,本节介绍常用的Lua开发方法。from:www.itpux.com
5.1 基本Lua脚本
# mkdir -p /data/openresty/lua
# 创建简单Lua脚本
# vi /data/openresty/lua/hello.lua
local function say_hello()
ngx.say(“Hello, OpenResty!”)
ngx.say(“Server: fgedudb01.fgedu.net.cn”)
ngx.say(“Time: “, ngx.now())
end
say_hello()
# 配置访问
# vi /usr/local/openresty/nginx/conf/conf.d/lua.conf
server {
listen 80;
server_name localhost;
location /hello {
default_type ‘text/plain’;
content_by_lua_file /data/openresty/lua/hello.lua;
}
}
# 重载配置
$ openresty -s reload
# 测试访问
$ curl http://192.168.1.51/hello
# 输出示例:
Hello, OpenResty!
Server: fgedudb01.fgedu.net.cn
Time: 1712205600
5.2 处理请求参数
# vi /data/openresty/lua/request.lua
local function handle_request()
local method = ngx.req.get_method()
local uri = ngx.var.uri
local args = ngx.req.get_uri_args()
ngx.say(“Request Method: “, method)
ngx.say(“Request URI: “, uri)
ngx.say(“Request Args:”)
for key, val in pairs(args) do
ngx.say(” “, key, ” = “, val)
end
if method == “POST” then
ngx.req.read_body()
local body = ngx.req.get_body_data()
ngx.say(“Request Body: “, body)
end
end
handle_request()
# 配置访问
# vi /usr/local/openresty/nginx/conf/conf.d/request.conf
server {
listen 80;
server_name localhost;
location /request {
default_type ‘text/plain’;
content_by_lua_file /data/openresty/lua/request.lua;
}
}
# 测试访问
$ curl “http://192.168.1.51/request?name=fengge&age=30”
# 输出示例:
Request Method: GET
Request URI: /request
Request Args:
name = fengge
age = 30
5.3 连接Redis
# vi /data/openresty/lua/redis.lua
local redis = require “resty.redis”
local red = redis:new()
red:set_timeout(1000)
local ok, err = red:connect(“127.0.0.1”, 6379)
if not ok then
ngx.say(“Failed to connect: “, err)
return
end
local res, err = red:auth(“fgedu123”)
if not res then
ngx.say(“Failed to auth: “, err)
return
end
res, err = red:set(“fgedu_key”, “fgedu_value”)
if not res then
ngx.say(“Failed to set: “, err)
return
end
ngx.say(“Set result: “, res)
res, err = red:get(“fgedu_key”)
if not res then
ngx.say(“Failed to get: “, err)
return
end
ngx.say(“Get result: “, res)
red:close()
# 配置访问
# vi /usr/local/openresty/nginx/conf/conf.d/redis.conf
server {
listen 80;
server_name localhost;
location /redis {
default_type ‘text/plain’;
content_by_lua_file /data/openresty/lua/redis.lua;
}
}
# 测试访问
$ curl http://192.168.1.51/redis
# 输出示例:
Set result: OK
Get result: fgedu_value
5.4 连接MySQL
# vi /data/openresty/lua/mysql.lua
local mysql = require “resty.mysql”
local db, err = mysql:new()
if not db then
ngx.say(“Failed to instantiate mysql: “, err)
return
end
db:set_timeout(1000)
local ok, err, errcode, sqlstate = db:connect({
host = “127.0.0.1”,
port = 3306,
database = “fgedudb”,
user = “fgedu”,
password = “fgedu123”,
charset = “utf8mb4”
})
if not ok then
ngx.say(“Failed to connect: “, err, “: “, errcode, ” “, sqlstate)
return
end
local res, err, errcode, sqlstate = db:query(“SELECT * FROM fgedu_users LIMIT 10”)
if not res then
ngx.say(“Bad result: “, err, “: “, errcode, ” “, sqlstate)
return
end
local cjson = require “cjson”
ngx.say(cjson.encode(res))
db:close()
# 配置访问
# vi /usr/local/openresty/nginx/conf/conf.d/mysql.conf
server {
listen 80;
server_name localhost;
location /mysql {
default_type ‘application/json’;
content_by_lua_file /data/openresty/lua/mysql.lua;
}
}
# 测试访问
$ curl http://192.168.1.51/mysql
# 输出示例:
[{“id”:1,”name”:”fengge”,”email”:”fengge@fgedu.net.cn”},{“id”:2,”name”:”admin”,”email”:”admin@fgedu.net.cn”}]
6. WAF防火墙配置
OpenResty非常适合构建WAF防火墙,本节介绍常用的WAF配置方法。更多学习教程www.fgedu.net.cn
6.1 基础WAF规则
# vi /data/openresty/lua/waf.lua
local _M = {}
local function check_sql_injection(str)
local sql_patterns = {
“select.+(from|limit)”,
“(?i:union.*select)”,
“(?i:insert.*into)”,
“(?i:delete.*from)”,
“(?i:update.*set)”,
“(?i:drop.*table)”,
“(?i:exec.*xp_)”,
“(?i:exec.*sp_)”,
“(?i:exec\\()”,
}
for _, pattern in ipairs(sql_patterns) do
if ngx.re.match(str, pattern, “jo”) then
return true
end
end
return false
end
local function check_xss(str)
local xss_patterns = {
“(?i:
“(?i:javascript:)”,
“(?i:onerror\\s*=)”,
“(?i:onload\\s*=)”,
“(?i:onclick\\s*=)”,
“(?i:alert\\()”,
}
for _, pattern in ipairs(xss_patterns) do
if ngx.re.match(str, pattern, “jo”) then
return true
end
end
return false
end
function _M.check()
local uri = ngx.var.uri
local args = ngx.req.get_uri_args()
if check_sql_injection(uri) then
ngx.log(ngx.WARN, “SQL Injection detected in URI: “, uri)
ngx.exit(403)
end
for key, val in pairs(args) do
if type(val) == “string” then
if check_sql_injection(val) then
ngx.log(ngx.WARN, “SQL Injection detected in args: “, key, “=”, val)
ngx.exit(403)
end
if check_xss(val) then
ngx.log(ngx.WARN, “XSS detected in args: “, key, “=”, val)
ngx.exit(403)
end
end
end
end
return _M
# 配置WAF
# vi /usr/local/openresty/nginx/conf/conf.d/waf.conf
server {
listen 80;
server_name localhost;
access_by_lua_block {
local waf = require “waf”
waf.check()
}
location / {
proxy_pass http://backend;
}
}
6.2 限流防护
# vi /data/openresty/lua/limit.lua
local limit_req = require “resty.limit.req”
local function limit_request()
local lim, err = limit_req.new(“limit”, 100, 200)
if not lim then
ngx.log(ngx.ERR, “Failed to instantiate a resty.limit.req object: “, err)
return ngx.exit(500)
end
local key = ngx.var.binary_remote_addr
local delay, err = lim:incoming(key, true)
if not delay then
if err == “rejected” then
ngx.log(ngx.WARN, “Request rejected for IP: “, ngx.var.remote_addr)
return ngx.exit(429)
end
ngx.log(ngx.ERR, “Failed to limit request: “, err)
return ngx.exit(500)
end
if delay >= 0.001 then
ngx.sleep(delay)
end
end
return {
limit_request = limit_request
}
# 配置限流
# vi /usr/local/openresty/nginx/conf/conf.d/limit.conf
server {
listen 80;
server_name localhost;
access_by_lua_block {
local limit = require “limit”
limit.limit_request()
}
location / {
proxy_pass http://backend;
}
}
7. 安全配置
OpenResty安全配置是保护Web服务的重要措施,本节介绍常用的安全配置方法。学习交流加群风哥微信: itpux-com
7.1 基本安全配置
# vi /usr/local/openresty/nginx/conf/conf.d/security.conf
server {
listen 80;
server_name secure.fgedu.net.cn;
# 隐藏版本号
server_tokens off;
# 安全头部
add_header X-Frame-Options “SAMEORIGIN” always;
add_header X-Content-Type-Options “nosniff” always;
add_header X-XSS-Protection “1; mode=block” always;
add_header Referrer-Policy “strict-origin-when-cross-origin” always;
add_header Content-Security-Policy “default-src ‘self'” always;
# 禁止访问隐藏文件
location ~ /\. {
deny all;
access_log off;
log_not_found off;
}
# 禁止访问敏感文件
location ~* \.(git|svn|htaccess|htpasswd|env|config|ini|log|sh|bak|sql)$ {
deny all;
access_log off;
log_not_found off;
}
location / {
proxy_pass http://backend;
}
}
# 重载配置
$ openresty -s reload
7.2 HTTPS配置
# mkdir -p /data/openresty/ssl
# openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
-keyout /data/openresty/ssl/fgedu.key \
-out /data/openresty/ssl/fgedu.crt \
-subj “/C=CN/ST=BJ/L=BJ/O=FGedu/OU=IT/CN=www.fgedu.net.cn”
# 配置HTTPS
# vi /usr/local/openresty/nginx/conf/conf.d/ssl.conf
server {
listen 443 ssl http2;
server_name www.fgedu.net.cn;
ssl_certificate /data/openresty/ssl/fgedu.crt;
ssl_certificate_key /data/openresty/ssl/fgedu.key;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
location / {
proxy_pass http://backend;
}
}
# HTTP重定向
server {
listen 80;
server_name www.fgedu.net.cn;
return 301 https://$server_name$request_uri;
}
# 重载配置
$ openresty -s reload
8. 监控与日志
OpenResty提供了完善的监控和日志功能,本节介绍常用的监控配置方法。更多学习教程公众号风哥教程itpux_com
8.1 状态监控
# vi /usr/local/openresty/nginx/conf/conf.d/status.conf
server {
listen 80;
server_name localhost;
location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;
allow 192.168.1.0/24;
deny all;
}
location /lua_status {
default_type ‘text/plain’;
content_by_lua_block {
local status = require “resty.status”
status.report()
}
}
}
# 重载配置
$ openresty -s reload
# 访问状态页面
$ curl http://192.168.1.51/nginx_status
# 输出示例:
Active connections: 10
server accepts handled requests
1000 1000 5000
Reading: 0 Writing: 1 Waiting: 9
8.2 Prometheus监控
# cd /usr/local/openresty/lualib
# git clone https://github.com/knyar/nginx-lua-prometheus.git prometheus
# 配置Prometheus指标
# vi /usr/local/openresty/nginx/conf/nginx.conf
http {
lua_shared_dict prometheus_metrics 10M;
init_by_lua_block {
local prometheus = require “prometheus”
local metrics = prometheus.init(“prometheus_metrics”)
_G.counter = metrics:counter(“nginx_http_requests_total”, “Total HTTP requests”, {“status”, “method”})
_G.histogram = metrics:histogram(“nginx_http_request_duration_seconds”, “HTTP request duration”, {“method”})
}
log_by_lua_block {
_G.counter:inc(1, {ngx.var.status, ngx.var.request_method})
_G.histogram:observe(ngx.now() – ngx.req.start_time(), {ngx.var.request_method})
}
}
# 暴露指标端点
# vi /usr/local/openresty/nginx/conf/conf.d/metrics.conf
server {
listen 9145;
server_name localhost;
location /metrics {
content_by_lua_block {
local prometheus = require “prometheus”
prometheus.collect()
}
}
}
# 访问指标
$ curl http://192.168.1.51:9145/metrics
# 输出示例:
# HELP nginx_http_requests_total Total HTTP requests
# TYPE nginx_http_requests_total counter
nginx_http_requests_total{status=”200″,method=”GET”} 1000
8.3 日志配置
# vi /usr/local/openresty/nginx/conf/nginx.conf
http {
log_format json escape=json ‘{‘
‘”time”:”$time_iso8601″,’
‘”remote_addr”:”$remote_addr”,’
‘”request”:”$request”,’
‘”status”:”$status”,’
‘”body_bytes_sent”:”$body_bytes_sent”,’
‘”request_time”:”$request_time”,’
‘”upstream_response_time”:”$upstream_response_time”‘
‘}’;
access_log /var/log/openresty/access.log json;
}
# Lua日志记录
# vi /data/openresty/lua/log.lua
local function log_request()
local log_data = {
time = ngx.now(),
remote_addr = ngx.var.remote_addr,
method = ngx.req.get_method(),
uri = ngx.var.uri,
status = ngx.var.status,
request_time = ngx.now() – ngx.req.start_time()
}
local cjson = require “cjson”
ngx.log(ngx.INFO, cjson.encode(log_data))
end
return {
log_request = log_request
}
# 使用日志
log_by_lua_block {
local log = require “log”
log.log_request()
}
9. 升级与迁移
OpenResty升级和迁移是运维工作中的重要环节,需要仔细规划和执行。from:www.itpux.com
9.1 版本升级
$ openresty -v
nginx version: openresty/1.21.4.3
# 备份配置
# tar -czf openresty_backup_$(date +%Y%m%d).tar.gz /usr/local/openresty /var/log/openresty
# 查看可用版本
# yum list openresty –showduplicates
# 升级OpenResty
# yum update openresty
# 输出示例:
Upgraded:
openresty-1.25.3.1-1.el8.x86_64
Complete!
# 验证版本
$ openresty -v
nginx version: openresty/1.25.3.1
# 检查配置
$ openresty -t
# 重启服务
# systemctl restart openresty
9.2 配置迁移
# tar -czf openresty_conf_backup_$(date +%Y%m%d).tar.gz \
/usr/local/openresty/nginx/conf \
/data/openresty/lua \
/var/log/openresty
# 迁移到新服务器
# scp openresty_conf_backup_*.tar.gz root@newserver:/backup/
# 在新服务器解压
# tar -xzf openresty_conf_backup_*.tar.gz -C /
# 检查配置
$ openresty -t
# 输出示例:
nginx: the configuration file /usr/local/openresty/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/openresty/nginx/conf/nginx.conf test is successful
# 启动服务
# systemctl start openresty
10. 生产环境实战案例
本节提供一个完整的生产环境配置案例,帮助读者更好地理解OpenResty的实际应用。更多学习教程www.fgedu.net.cn
10.1 生产环境完整配置
# vi /usr/local/openresty/nginx/conf/nginx.conf
user openresty;
worker_processes auto;
worker_rlimit_nofile 65535;
error_log /var/log/openresty/error.log warn;
pid /usr/local/openresty/nginx/logs/nginx.pid;
events {
worker_connections 65535;
use epoll;
multi_accept on;
}
http {
include mime.types;
default_type application/octet-stream;
charset utf-8;
server_tokens off;
log_format json escape=json ‘{‘
‘”time”:”$time_iso8601″,’
‘”remote_addr”:”$remote_addr”,’
‘”request”:”$request”,’
‘”status”:”$status”,’
‘”request_time”:”$request_time”‘
‘}’;
access_log /var/log/openresty/access.log json;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
gzip on;
gzip_vary on;
gzip_types text/plain text/css application/json application/javascript;
lua_package_path “/usr/local/openresty/lualib/?.lua;/data/openresty/lua/?.lua;;”;
lua_package_cpath “/usr/local/openresty/lualib/?.so;;”;
lua_shared_dict cache 100m;
lua_shared_dict limit 10m;
lua_code_cache on;
init_by_lua_block {
require “resty.core”
}
include conf.d/*.conf;
}
10.2 API网关配置
# vi /usr/local/openresty/nginx/conf/conf.d/api.conf
upstream backend_servers {
server 192.168.1.51:8080 weight=3;
server 192.168.1.52:8080 weight=2;
server 192.168.1.53:8080 weight=1;
keepalive 32;
}
server {
listen 80;
server_name api.fgedu.net.cn;
access_by_lua_block {
local waf = require “waf”
waf.check()
local limit = require “limit”
limit.limit_request()
local auth = require “auth”
auth.check_token()
}
location / {
proxy_pass http://backend_servers;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Connection “”;
}
log_by_lua_block {
local log = require “log”
log.log_request()
}
}
10.3 性能调优实战
# vi /etc/sysctl.d/99-openresty.conf
net.core.somaxconn = 65535
net.core.netdev_max_backlog = 65535
net.ipv4.tcp_max_syn_backlog = 65535
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 30
fs.file-max = 2097152
# 使配置生效
# sysctl -p /etc/sysctl.d/99-openresty.conf
# 用户限制
# vi /etc/security/limits.d/openresty.conf
openresty soft nofile 65535
openresty hard nofile 65535
# 压力测试
$ ab -n 100000 -c 1000 http://192.168.1.51/api/users
# 输出示例:
Server Software: openresty/1.25.3.1
Server Hostname: 192.168.1.51
Server Port: 80
Concurrency Level: 1000
Time taken for tests: 10.000 seconds
Complete requests: 100000
Failed requests: 0
Requests per second: 10000.00 [#/sec] (mean)
本文由风哥教程整理发布,仅用于学习测试使用,转载注明出处:http://www.fgedu.net.cn/10327.html
