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

e2e5950c03ed804c3e049dd8e8b89bdc.png

简介

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的前端渲染的功能。

电商网站使用场景

电商网站pcwap首页及商品详情页生成静态页后,存储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 seclocal ok, err = red:connect("实际ip", 6379)if not ok then    ngx.say("failed to connect: ", err)    returnend--如果设置了密码请打开注释,并填写密码local res, err = red:auth("实际密码")if not res thenngx.say("failed to authenticate: ", err)returnendlocal res, err = red:get(request_uri)-- 请修改https://www.test.com 为实际配置域名或IP端口if res == ngx.null thenngx.say(request_uri)    -- ngx.redirect("http://实际ip/404.html")   returnendif not res then    ngx.say("failed to get: " .. request_uri , err)    returnendred: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.htmlhttp://ip:8081/WAP/index.html

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

实际效果如:

2ffcd3ce812629e9756d4b878f9f23b2.png

基于Nginx+Lua的总结

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值