一、OpenResty概述
OpenResty是一个基于Nginx与Lua的高性能Web平台,集成了大量精良的Lua库、第三方模块,用于构建高性能动态Web应用、API网关等。
风哥风哥提示:
1.1 OpenResty核心特性
- 高性能:基于Nginx事件模型,支持高并发
- Lua脚本:内置LuaJIT,支持动态脚本
- 丰富模块:集成Redis、MySQL、Memcached等客户端
- API网关:适合构建API网关和微服务架构
二、OpenResty安装部署
2.1 YUM安装
# 添加OpenResty仓库
yum install -y yum-utils
yum-config-manager --add-repo https://openresty.org/package/centos/openresty.repo
# 安装OpenResty
yum install -y openresty
# 安装Resty命令行工具
yum install -y openresty-resty
# 启动服务
systemctl start openresty
systemctl enable openresty
# 查看版本
openresty -v
# 输出示例
nginx version: openresty/1.25.3.1
nginx version: openresty/1.25.3.1
三、Lua基础语法
3.1 Lua基本语法
-- 变量定义
local name = "OpenResty"
local count = 100
-- 表(Table)
local user = {
id = 1,
name = "风哥1号",
age = 30
}
-- 函数
local function add(a, b)
return a + b
end
-- 条件判断
if score >= 90 then
print("优秀")
elseif score >= 60 then
print("及格")
end
-- 循环
for i = 1, 10 do
print(i)
end
3.2 OpenResty常用API
-- 获取请求参数
local args = ngx.req.get_uri_args()
local name = args["name"]
-- 输出响应
ngx.say("Hello, OpenResty!")
ngx.exit(200)
-- 日志输出
ngx.log(ngx.ERR, "错误日志")
ngx.log(ngx.INFO, "信息日志")
-- JSON编解码
local json = require("cjson")
local encoded = json.encode({name = "风哥1号"})
local decoded = json.decode('{"name":"风哥1号"}')
四、Nginx配置与Lua集成
4.1 基本配置
# nginx.conf
http {
lua_package_path "/usr/local/openresty/lualib/?.lua;;";
lua_shared_dict cache 128m;
server {
listen 80;
location / {
content_by_lua_block {
ngx.say("<h1>Hello OpenResty!</h1>")
}
}
location /api {
content_by_lua_file lua/api.lua;
}
}
}
五、API网关实现
5.1 路由配置
-- lua/router.lua
local routes = {
["/api/users"] = {handler = "api.users"},
["/api/orders"] = {handler = "api.orders"}
}
function route()
local uri = ngx.var.uri
local route = routes[uri]
if route then
local handler = require(route.handler)
handler.process()
end
end
5.2 认证中间件
-- lua/auth.lua
local jwt = require("resty.jwt")
function verify_token()
local auth_header = ngx.req.get_headers()["Authorization"]
if not auth_header then
ngx.status = 401
ngx.say('{"error": "Unauthorized"}')
return ngx.exit(401)
end
local token = auth_header:match("Bearer%s+(.+)")
local jwt_obj = jwt:verify("secret", token)
if not jwt_obj.verified then
ngx.status = 401
return ngx.exit(401)
end
ngx.ctx.user = jwt_obj.payload
end
六、Redis集成
6.1 Redis操作
local redis = require("resty.redis")
local red = redis:new()
red:connect("127.0.0.1", 6379)
-- 设置值
red:set("key", "value")
red:setex("key", 3600, "value")
-- 获取值
local value = red:get("key")
-- 删除
red:del("key")
-- 设置过期时间
red:expire("key", 3600)
-- 连接池
red:set_keepalive(10000, 100)
七、MySQL集成
7.1 MySQL操作
local mysql = require("resty.mysql")
local db, err = mysql:new()
db:connect({
host = "127.0.0.1",
port = 3306,
database = "test",
user = "root",
password = "password"
})
-- 查询
local res = db:query("SELECT * FROM users WHERE id = 1")
-- 插入
db:query("INSERT INTO users(name, email) VALUES('风哥1号', 'test@fgedu.net.cn')")
-- 更新
db:query("UPDATE users SET name='风哥2号' WHERE id=1")
-- 连接池
db:set_keepalive(10000, 100)
八、限流与缓存
8.1 限流配置
local limit_req = require("resty.limit.req")
local lim = limit_req.new("limit", 100, 200)
local key = ngx.var.binary_remote_addr
local delay, err = lim:incoming(key, true)
if not delay then
if err == "rejected" then
ngx.status = 429
ngx.say('{"error": "Too Many Requests"}')
return ngx.exit(429)
end
end
8.2 缓存实现
local cache = ngx.shared.cache
-- 设置缓存
cache:set("key", "value", 3600)
-- 获取缓存
local value = cache:get("key")
-- 删除缓存
cache:delete("key")
-- 缓存穿透保护
local value = cache:get("key")
if not value then
value = query_from_db()
cache:set("key", value, 3600)
end
九、性能优化
9.1 连接池配置
# nginx.conf
http {
lua_socket_pool_size 100;
lua_socket_connect_timeout 3s;
lua_socket_send_timeout 3s;
lua_socket_read_timeout 3s;
lua_socket_buffer_size 4k;
}
9.2 性能调优
# nginx.conf
worker_processes auto;
worker_cpu_affinity auto;
events {
worker_connections 65535;
multi_accept on;
}
http {
lua_max_pending_timers 1024;
lua_max_running_timers 256;
lua_shared_dict cache 256m;
lua_shared_dict limit 10m;
}
十、运维命令
10.1 常用管理命令
# 测试配置
openresty -t
# 重载配置
openresty -s reload
# 使用resty命令执行Lua
resty -e 'print("Hello")'
# 查看进程
ps -ef | grep nginx
# 查看连接
ss -tlnp | grep 80
十一、最佳实践
| 配置项 | 建议值 | 说明 |
|---|---|---|
| worker_processes | auto | 自动匹配CPU核心 |
| lua_shared_dict | 128m+ | 共享内存大小 |
| 连接池大小 | 100 | 数据库连接池 |
注意事项:
- 合理使用连接池避免连接泄漏
- 缓存数据需要设置过期时间
- 错误处理要完善
- 监控Lua代码执行时间
十二、总结
OpenResty是构建高性能Web应用和API网关的重要平台。通过本培训文档,您应该掌握了:
- OpenResty的安装部署
- Lua基础语法和OpenResty API
- API网关的实现方法
- Redis和MySQL集成
- 限流和缓存配置
- 性能优化和运维管理
IT运维培训文档系列 | 第253篇 | OpenResty平台培训
本文由风哥教程整理发布,仅用于学习测试使用,转载注明出处:http://www.fgedu.net.cn/10327.html
