Nginx静态化html本地缓存处理

本文介绍了如何配置Nginx的lua.conf文件以实现本地缓存和通过lua脚本处理HTTP请求。通过lua_shared_dict配置缓存,然后在location块中使用content_by_lua_file调用lua脚本来处理goods.lua中的逻辑,该脚本从远程API获取数据并缓存,再使用lua-resty-template库渲染goods.html模板。示例还展示了goods.html的结构和后端Java控制器的代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.Nginx的conf文件目录新建lua.conf:

在nginx.conf同一级目录来一个lua.conf:

lua.conf:

lua_shared_dict my_cache 128m; #这个是配置Nginx本地缓存

server {
        listen       80;
        server_name  localhost;
        # first match ngx location  首选匹配模板路径(找Html)
       set $template_location "/templates";
       # then match root read file  首选匹配不到模板路径就到template_root下面去找(找Html)
       set $template_root "/usr/local/openresty/nginx/html/templates";
       
       #不写上面这个html的匹配路径的话,默认是从nginx目录下html里面获取
       #通常都会配置自己的存放路径

        location /goods{  #开始配置自己的访问路径规则
           default_type text/html;  #这里是渲染html页面的关键,很多人漏了这个或者写成别的类型导致渲染失败
           content_by_lua_file /usr/local/openresty/nginx/lua/goods.lua;

        }
}

2.配置好了的lua.conf 在nginx.conf中引用

 

#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;
    lua_code_cache off; #关闭lua缓存 重启后生效 
    charset utf-8; #编码格式
    include lua.conf;


    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;
    

    server {
        listen       80;
        server_name  localhost;
        #charset koi8-r;

        #access_log  logs/host.access.log  main;

      #  location / {
        #    proxy_pass  http://172.16.21.58:9999;
        #    root   html;
      #      index  index.html index.htm;
       # }

        location /lua{
           default_type text/html;       
           content_by_lua_file /usr/local/openresty/nginx/lua/luatest.lua;
        }


        location /luaOut{
           default_type text/plain;       
           content_by_lua  'ngx.say("hello lua")';
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

}

3.goods.lua:这里就是对后台发送请求或群数据渲染模板操作:

 

--Nginx本地缓存处理
local uri_args = ngx.req.get_uri_args()
local goodsId = uri_args ["goodsId"]    --这个是获取请求的url参数
local cache_ngx = ngx.shared.my_cache   --这是我们在lua.conf配置的本地缓存
local goodsCacheKey =  "Goods"..goodsId 
local goodsCache = cache_ngx:get(goodsCacheKey )
--判断是否有缓存
if goodsCache == "" or goodsCache  == nil then
--发送http请求
local http = require("resty.http")
local httpc =http.new()
local resp,err=httpc:request_uri("http://172.16.21.58:9999",{
    method="GET",
    path="/goodsCache/get/goods/"..goodsId ,
    keepalive=false
})
goodsCache = resp.body   --得到请求响应结果
-- local expireTime=math.random(10,20) --随机时间
cache_ngx:set(goodsCacheKey ,goodsCache,10)   --这个过期时间要随机设置 防止并发对机器的负载过大
--ngx.say("No Cache");
--ngx.say(goodsCache);
end


--JSON化处理
local cjson = require("cjson")
local goodsJson=cjson.decode(goodsCache)

local context = {
goodsId=goodsJson.goodsId,
goodsName=goodsJson.goodsName,
price=goodsJson.price,
desc=goodsJson.desc,
}


--ngx.say("Having Cache");
--ngx.say(goodsCache);


local template =  require("resty.template")
template.render("goods.html",context)

这里需要引入lua包:

http.lua:https://github.com/ledgetech/lua-resty-http

http_headers.lua:https://github.com/ledgetech/lua-resty-http

template.lua:https://github.com/bungle/lua-resty-template

这三个包放入:/usr/local/openresty/lualib/resty下面   这是我安装的openresty的目录

4.goods.html:

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
    <title>{*goodsName*}</title>
</head>
<body>
商品ID: {*goodsId*}</br>
商品名称: {*goodsName*}</br>
商品价格: {*price*}</br>
商品简介: {*desc*}
</body>
</html>

注:这里的goods.html就是我们在lua.conf配置的template_location或者template_root目录下面

5.后台请求:

package com.zking.controller;

import com.zking.pojo.GoodsInfo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: codinglife
 * @time: 2020/12/14 13:51
 */
@Controller
@RequestMapping("/goodsCache")
public class GoodsCacheController {


    @GetMapping("/get/goods/{goodsId}")
    @ResponseBody
    public GoodsInfo getGoodsInfo(@PathVariable String goodsId){

            GoodsInfo goodsInfo=new GoodsInfo();
            goodsInfo.setGoodsId(goodsId+"");
            goodsInfo.setGoodsName("华为P"+goodsId);
            goodsInfo.setDesc("这是一款华为的产品"+goodsId);
            goodsInfo.setPrice(Integer.valueOf(goodsId));

        return goodsInfo;

    }

}

6.结果:

 

         

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值