首页 服务器技术 nginx

企业级电商网站使用Nginx+Lua(OpenResty)实现高性能Web应用



简介

OpenResty是一款基于Nginx的高性能负载均衡服务器容器,简单来说是Nginx+Lua。结合了Lua语言来对Nginx进行扩展,使得在Nginx上具有web容器功能。

使得可以使用lua脚本来进行web的开发。有了lua,我们可以借助于nginx的异步非阻塞的功能,达到使用 lua 异步并发访问后端的 MySQL, Memcached, Redis等等服务。

OpenResty 架构的web可以轻松超越Node.js的性能,并且对后端语言没有限制,你可以使用Java/PHP/Python等等各种语言。OpenResty(nginx+lua)可以替代node.js的前端渲染的功能。

电商网站使用场景

电商网站pc\wap首页及商品详情页生成静态页后,存储Redis上,然后通过OpenResty(nginx+lua脚本)从Redis读取静态页,前端渲染,展示给用户。提升页面访问速度及高并发。

OpenResty运行环境搭建

这里采用docker方式安装

拉取镜像

docker pull openresty/openresty:1.15.8.2-7-centos

启动openresty

端口映射为 8081,映射配置目录便于修改配置

docker run --rm -d --name openresty -p 8081:80 
-v /opt/deploy-script/openresty/:/usr/local/openresty/nginx/conf/ 
openresty/openresty:1.15.8.2-7-centos

编写lua脚本


/opt/deploy-script/openresty/lua 目录下 新建.lua 文件,并添加如下内容

local request_uri = ngx.var.uri 
local redis = require "resty.redis"
local red = redis:new()
--red:set_timeout(10000) -- 1 sec
local ok, err = red:connect("实际ip", 6379)
if not ok then
    ngx.say("failed to connect: ", err)
    return
end
--如果设置了密码请打开注释,并填写密码
local res, err = red:auth("实际密码")
if not res then
	ngx.say("failed to authenticate: ", err)
	return
end
local res, err = red:get(request_uri)
-- 请修改https://www.test.com 为实际配置域名或IP端口
if res == ngx.null then
	ngx.say(request_uri)
    -- ngx.redirect("http://实际ip/404.html")
   return
end
if not res then
    ngx.say("failed to get: " .. request_uri , err)
    return
end
red:set_keepalive(6000,1000)
ngx.say(res)


/opt/deploy-script/openresty 目录下 新建nginx.conf文件,并添加如下内容

#新建静态页输出节点,content_by_lua_file为lua脚本实际路径。   
server {
        listen       80;
        server_name  localhost; 
        #pc端静态响应
        location /PC {
           default_type text/html;
           content_by_lua_file "/usr/local/openresty/nginx/conf/lua/single_connector.lua"; 
           #redis集群请使用此配置 
           #content_by_lua_file "/usr/local/openresty/nginx/conf/lua/cluster_connector.lua";  
        }
        #wap端静态响应
        location /WAP {
           default_type text/html;
           content_by_lua_file "/usr/local/openresty/nginx/conf/lua/single_connector.lua";  
          #redis集群请使用此配置 
          #content_by_lua_file "/usr/local/openresty/nginx/conf/lua/cluster_connector.lua";  
        }
    }

重启openresty

验证

首先在redis中执行如下命令:

set /PC/index.html 'hello pc'
set /WAP/index.html 'hello wap'

然后分别访问:

http://ip:8081/PC/index.html
http://ip:8081/WAP/index.html

实际应用是在应用系统后台,商品上架时触发,根据详情页模板读取动态数据,生成商品详情页,然后详情页保存到redis,通过lua读取渲染展示给用户查看。

实际效果如:



基于Nginx+Lua的总结

个人认为适合开发业务逻辑单一、特定性能提升场景、核心代码行数较少的应用,不适合业务逻辑复杂、功能繁多的业务型或者企业级应用。

相关推荐