Nginx静态化html本地缓存处理

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.结果:

 

         

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Nginx是一个高性能的Web服务器和反向代理服务器。对于静态资源的特殊处理Nginx提供了一些功能和配置选项。 1. 路径匹配:Nginx可以根据静态资源的路径进行匹配,例如通过使用location指令,可以设定不同的路径匹配规则。例如,可以使用`location /img/`来匹配所有以/img/开头的URL,然后针对这些URL进行特殊处理。 2. 压缩:Nginx可以对静态资源进行gzip压缩,以减小文件的大小,提高传输速度。通过在配置文件中开启gzip功能,并设置适当的压缩级别和文件类型,可以实现对特定类型的静态文件进行压缩处理。 3. 缓存Nginx可以配置静态资源缓存有效期,以减少对服务器的请求。通过设置expires或者add_header指令,可以控制浏览器缓存静态资源的时间。 4. 图片处理Nginx提供了图像处理的能力,可以在不使用其他图像服务器的情况下对图像进行调整和处理。通过使用ngx_http_image_filter_module模块,可以实现图像缩放、裁剪、旋转等操作。 5. 文件访问控制:Nginx可以根据特定需求对静态资源进行访问控制。可通过配置username_password文件进行基本身份验证,或使用access指令进行访问限制。 总之,Nginx处理静态资源时的特殊处理方面有多种选项可供选择。通过路径匹配、压缩、缓存、图片处理和文件访问控制等功能,可以有效地提升静态资源处理性能和访问效率。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值