编程技术分享平台

网站首页 > 技术教程 正文

高并发开发,第五章【openresty】,商品详情的页面静态化

xnh888 2024-10-12 12:52:20 技术教程 18 ℃ 0 评论

前言

在互联网项目中,某些页面(如首页、热门资讯页等)可能会面临大量的用户访问请求。这些请求如果都通过动态生成的方式来处理,会对服务器造成巨大的压力,并可能导致响应速度变慢。

通过openresty 模板引擎lua-resty-template实现 页面静态化,将这些频繁访问的页面提前生成静态HTML文件,并部署在静态资源服务器上当用户访问这些页面时,可以直接从静态资源服务器获取内容,而无需经过复杂的动态生成过程。这样可以显著提高响应速度,并减轻服务器的压力。

实践

1. 商品详情模版

2. Lua 脚本(处理商品详情的静态化)

-- /usr/local/openresty/script/product_detail.lua
local product_id = ngx.var.product_id
local cache_key = "product_detail_" .. product_id
local product_detail = ngx.shared.product_cache:get(cache_key)

if product_detail then
    -- 缓存命中,直接返回静态化内容
    ngx.say(product_detail)
    return
end

-- 缓存未命中,请求后端服务获取数据
local backend_url = "http://backend-service/dynamic?product_id=" .. product_id
local res = ngx.location.capture(backend_url)

if res.status == 200 then
    -- 获取数据成功,生成静态内容并缓存
    local static_content = res.body
    ngx.shared.product_cache:set(cache_key, static_content, 300) -- 缓存5分钟
    ngx.say(static_content)
else
    -- 后端服务未找到数据,返回错误
    ngx.status = ngx.HTTP_NOT_FOUND
    ngx.say("Product not found")
end



3 访问配置

        location /product {
           -- 将参数id  赋值给变量product_id
            set $product_id $arg_id;
            content_by_lua_file /usr/local/openresty/script/product_detail.lua;
        }

4 可以设置NGINX混存

lua_shared_dict product_cache 10m;

5 访问商品详情

http://server.com/product?id=123

6 结果


最后

希望大家在工作中遇到高并发的场景,尽可能的将页面静态化,增加响应速度。

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表