OpenResty与Lua实现高并发请求处理

本文涉及的产品
Redis 开源版,标准版 2GB
推荐场景:
搭建游戏排行榜
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS MySQL,高可用系列 2核4GB
简介: OpenResty与Lua实现高并发请求处理

OpenResty与Lua实现高并发请求处理


前言

官网:http://openresty.org/cn/


介绍

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 软件后,因为 OpenResty 基于 Nginx 开发,所以配置 OpenResty 只需要配置 Nginx 即可。


在 OpenResty 安装目录下配置 nginx

# nginx 拦截 /update_context 请求,交给 lua 脚本处理
location /update_context {
  content_by_lua_file /root/lua/update_content.lua
}
location /get_context {
  content_by_lua_file /root/lua/get_content.lua
}

Lua 脚本

lua redis 脚本参考:https://github.com/openresty/lua-resty-redis


lua mysql 脚本参考:https://github.com/openresty/lua-resty-mysql


update_content.lua 脚本

ngx.header.content_type="application/json;charset=utf8"
local cjson = require("cjson")
local mysql = require("resty.mysql")
-- 获取用户的请求参数
local uri_args = ngx.req.get_uri_args()
-- 获取请求参数中的 id
local id = uri_args["id"]
-- 连接 mysql
local db = mysql:new()
db:set_timeout(1000)
local props = {
    host = "192.168.8.4",
    port = 3306,
    database = "changgou_content",
    user = "root",
    password = "123456"
}
-- 查询mysql
local res = db:connect(props)
local select_sql = "select url,pic from tb_content where status = '1' and category_id =" ..id.." order by sort_order"
res = db:query(select_sql)
db:close()
-- 连接redis
local redis = require "resty.redis"
local red = redis:new()
red:set_timeouts(1000, 1000, 1000)
local ok, err = red:connect("192.168.8.4", 6379)
if not ok then
    ngx.say("failed to connect: ", err)
    return
end
red:set("content_"..id, cjson.encode(res))
red:close()
ngx.say("{flag:true}")

get_content.lua 脚本

ngx.header.content_type="application/json;charset=utf8"
local cjson = require("cjson")
local mysql = require("resty.mysql")
local uri_args = ngx.req.get_uri_args()
local id = uri_args["id"]
-- 获取nginx缓存数据,如果没有从redis中获取
-- 需要定义 ngx.shared.dis_cache 模块,lua 缓存命名空间(dis_cache)
local cache_ngx = ngx.shared.dis_cache;
local contentCache = cache_ngx:get("content_"..id)
if contentCache == "" or contentCache == nil then
    ngx.say("contentCache not found ")
else
    ngx.say(contentCache)
    return
end
-- 连接redis
local redis = require "resty.redis"
local red = redis:new()
red:set_timeouts(1000, 1000, 1000)
local ok, err = red:connect("192.168.8.4", 6379)
if not ok then
    ngx.say("failed to connect: ", err)
    return
end
-- 从 redis 中获取数据
local res, err = red:get("content_"..id)
if not res then
    ngx.say("failed to get content_"..id, err)
    return
end
if res == ngx.null then
    ngx.say("content_"..id.." not found.")
    -- redis缓存中没有连接数据库查询,并放入redis缓存中
    local db = mysql:new()
    local props = {
        host = "192.168.8.4",
        port = 3306,
        database = "changgou_content",
        user = "root",
        password = "123456"
    }
    local ok, err, errcode, sqlstate = db:connect(props)
    if not ok then
        ngx.say("failed to connect: ", err, ": ", errcode, " ", sqlstate)
        return
    end
    ngx.say("connected to mysql.")
     local select_sql = "select url,pic from tb_content where status = '1' and category_id =" ..id.." order by sort_order"
    local res, err, errcode, sqlstate = db:query(select_sql)
    if not res then
        ngx.say("bad result: ", err, ": ", errcode, ": ", sqlstate, ".")
        return
    end
    -- 设置缓存到 nginx 中, 10*60: 10分钟
    cache_ngx:set("content_"..id, res, 10*60)
    -- 存入缓存到 redis 中
    red:set("content_"..id, cjson.encode(res))
    -- 输出
    ngx.say("content_"..id, cjson.encode(res))
    db:close()
    return
end
-- 设置缓存到 nginx 中
cache_ngx:set("content_"..id, res, 10*60)
ngx.say("content_"..id, res)
red:close()


定义 ngx.shared.dis_cache 模块 ,需要在 nginx 配置文件中的 http 模块下添加

# 定义 lua 缓存命名空间(dis_cache)及其大小(128m)
lua_shared_dict dis_cache 128m;


如图


image.png

目录
相关文章
|
存储 缓存 Java
Openresty(lua+nginx)-Guava-Redis做多级缓存
Openresty(lua+nginx)-Guava-Redis做多级缓存
260 1
|
缓存 NoSQL 中间件
redis如何通过读写分离来承载读请求高并发
redis如何通过读写分离来承载读请求高并发
222 0
浅谈基于openresty(nginx+lua)开发轻量级,按流量控制的灰度模块(下)
浅谈基于openresty(nginx+lua)开发轻量级,按流量控制的灰度模块
284 0
|
缓存 安全 API
【亿级数据专题】「高并发架构」盘点本年度探索对外服务的百万请求量的API网关设计实现
公司对外开放的OpenAPI-Server服务,作为核心内部系统与外部系统之间的重要通讯枢纽,每天处理数百万次的API调用、亿级别的消息推送以及TB/PB级别的数据同步。经过多年流量的持续增长,该服务体系依然稳固可靠,展现出强大的负载能力。
473 9
【亿级数据专题】「高并发架构」盘点本年度探索对外服务的百万请求量的API网关设计实现
|
1月前
|
存储 监控 NoSQL
140_异步推理:队列管理框架 - 使用Celery处理高并发请求的独特设计
在大型语言模型(LLM)部署的实际场景中,推理服务的并发处理能力直接影响用户体验和系统稳定性。随着LLM应用的普及,如何高效处理大量并发请求成为部署优化中的关键挑战。传统的同步请求处理方式在面对突发流量时容易导致系统过载,响应延迟增加,甚至服务崩溃。异步推理通过引入队列管理机制,能够有效缓冲请求峰值,平滑系统负载,提高资源利用率,从而为LLM服务提供更稳定、更高效的并发处理能力。
|
5月前
|
缓存 NoSQL 算法
高并发秒杀系统实战(Redis+Lua分布式锁防超卖与库存扣减优化)
秒杀系统面临瞬时高并发、资源竞争和数据一致性挑战。传统方案如数据库锁或应用层锁存在性能瓶颈或分布式问题,而基于Redis的分布式锁与Lua脚本原子操作成为高效解决方案。通过Redis的`SETNX`实现分布式锁,结合Lua脚本完成库存扣减,确保操作原子性并大幅提升性能(QPS从120提升至8,200)。此外,分段库存策略、多级限流及服务降级机制进一步优化系统稳定性。最佳实践包括分层防控、黄金扣减法则与容灾设计,强调根据业务特性灵活组合技术手段以应对高并发场景。
1562 7
|
网络协议
Lua中实现异步HTTP请求的方法
Lua中实现异步HTTP请求的方法
|
缓存 负载均衡 API
抖音抖店API请求获取宝贝详情数据、原价、销量、主图等参数可支持高并发调用接入演示
这是一个使用Python编写的示例代码,用于从抖音抖店API获取商品详情,包括原价、销量和主图等信息。示例展示了如何构建请求、处理响应及提取所需数据。针对高并发场景,建议采用缓存、限流、负载均衡、异步处理及代码优化等策略,以提升性能和稳定性。
|
11月前
|
Web App开发 网络安全 数据安全/隐私保护
Lua中实现HTTP请求的User-Agent自定义
Lua中实现HTTP请求的User-Agent自定义
|
存储 JSON Ubuntu
如何使用 Lua 脚本进行更复杂的网络请求,比如 POST 请求?
如何使用 Lua 脚本进行更复杂的网络请求,比如 POST 请求?

热门文章

最新文章

下一篇
oss云网关配置