“This is my 22nd day of participating in the First Wen Challenge 2022.First challenge in 2022”

Openresty pages are static and multilevel cached

Multi-level cache:

  • The benefits of data caching need not be introduced. , the so-called multi-level cache, that is, the data is cached at different system levels in the entire system architecture to improve access efficiency, which is one of the most widely used solutions.
  • Nginx can cache data,Cache in memory, improve program performance!There are a number of techniques that can be used to cache applicationsMultistage cache And different caching technologies exist, in different places.. Achieve different functions!
  • As far as I know, caching can be done:Nginx — Elasticearch — redis — @ehCache JVM cache — Mybatis also has secondary cache!Too strong! Of course, this chapter will not cover that much, but to pick out a few:Nginx redis@ehCache JVM cache

Page staticsTemplate rendering

  • Dynamic Web page development is a common scene in Web development, such as jingdong commodity details page, whose page logic is very complex and needs to use template technology to achieve. Lua also has a number of templating engines, lua-resty-Template, that can render very complex pages, with acceptable performance with LuaJIT.

What is a dynamic page? What is a static page?

  • Dynamic web pages:.asp,.jsp,.php, perl,.cgi and other forms as suffixes, according to the user’s different operations, present different data to the user; Eg: The browser search ~ input different keywords will present different content to the user;
  • Static pages: Static pages exist and are loaded directly to the client’s browser without being compiled by the server. Static pages need to occupy a certain server space, and can not independently manage the release of updated pages, if you want to update the content of the web page, through FTP software to put the file DOWN with web page production software modification (through fSO and other technical exceptions) common static pages example:.html extension,.htm extension
  • In addition to static pages and dynamic pages there is a pseudo static page, when the site page conversion into mostPseudo static pages.

Why do pages need to be static

  • Webpage static is beneficial to search engine collectionFor static and dynamic pages,Search engines prefer static pagesFor static pages also better capture included, so there are great benefits for website optimization,Better for rankingYou can go to observe those large portal sites, such as Sina, Alibaba, Baidu and other pages mostly use static or pseudo static pages to display, it can be imagined that this is enough to show that static brings great benefits to the site.
  • Static pages are conducive to the stability of the website. First of all, from a security point of view, static pages are not vulnerable to hacker attacks. Hackers can not see the background of your website, website procedures and database addresses from your website, so that it is much safer than dynamic pages.There is a static page because the program, database and other problems, affect the normal opening of the siteStatic pages will make your site more stable and increase your trust.
  • Page static is conducive to improving the speed of SEO website optimization is a very important factor is the speed of the website open, open faster, SEO optimization effect is better…It is well known that dynamic pages are opened to call the database content, which affects the speed of the site, while static pages are not needed, reducing the link and improving the speed of the site.

Examples of the Demo

Boot Multi-level cache Settings:

Here’s how Redis and Ehcache cache Java code:Not elaboratingIt can be understood:Click on the

  • Service layer — Controller layer — data display!

Nginx cache + page static processing:

Mostly lua, of course...

info.lua

 -- Chinese transcoding
 ngx.header.content_type="text/html; charset=utf8"
 Get url parameters
 local uri_args = ngx.req.get_uri_args()
 local goodsId = uri_args["goodsId"]
 -- Print logs
 ngx.log(ngx.ERR,"json------",goodsId)
 ​
 local cache_ngx = ngx.shared.my_cache               -- Nginx cache template object
 local goodsCacheKey = "goods:"..goodsId             - set up the key
 local goodsCache = cache_ngx:get(goodsCacheKey)     - according to a get (key); Get cached data!
 -- Determine if there is data "" or nil and send the request....
 if goodsCache == "" or goodsCache == nil then
 local http = require("resty.http")
 local httpc = http.new()
 local resp, err = httpc:request_uri("http://127.0.0.1:6001",{
  method = "GET".path = "/showinfo/"..goodsId
 })
 -- Get results
 goodsCache = resp.body
 Set the cache time
 local expireTime = math.random(600.1200)
 -- set(key,value); Set the cache
 cache_ngx:set(goodsCacheKey,goodsCache,expireTime)
 end
 ​
 -- Log Output
 ngx.log(ngx.ERR,"json------",goodsCache)
 Get JSON template!
 local cjson = require("cjson")
 local goodsCacheJSON = cjson.decode(goodsCache) The resulting data is converted to JSON
 The response parameter encapsulates the context
 local context = {
 goodsname = goodsCacheJSON.spu.name,
 img = goodsCacheJSON.spu.images,
 introduction = goodsCacheJSON.spu.introduction,
 specItems = goodsCacheJSON.spu.specItems
 }
 Get the template object.
 local template = require("resty.template")
 template.render("item.html", context)           -- Context passes in the specified template static page!
Copy the code

The cache

 local cache_ngx = ngx.shared.my_cache               -- Nginx cache template object
 ​
 local goodsCache = cache_ngx:get(goodsCacheKey)     - according to a get (key); Get cached data!
 -- Determine if there is data "" or nil and send the request....
 if goodsCache == "" or goodsCache == nil then
     -- Request data through the set method, according to the specified key set cache/cache time (recommended random buffer avalanche!)
     Set the cache time
     local expireTime = math.random(600.1200)
     -- set(key,value); Set the cache
     cache_ngx:set(goodsCacheKey,goodsCache,expireTime)
 end
Copy the code

Ok. That’s the basic syntax for nginx cache Settings…Overall not hard!

Page static processing

Nginx lua is implemented with: lua-resty-templateThe general contents include:

  • Template location: Where to find templates;
  • Variable output/escape: variable value output;
  • Code snippets: Execute code snippets, complete complex logic such as if/else, for, call object functions/methods;
  • Comments: Explain the meaning of code snippets;
  • Include: Includes another template fragment;

Templates location

  • We need to tell lua-resty-template where to load our moduleThis can be accessed throughSet instruction definition Template_location, template_root Or use Loaded at the location defined by the root directive

Configuration file for nginx execution: specify the template location lua.conf under this request

# save to nginx128MB cache size! Used to store hot data (frequently used data!) lua_shared_dict my_cache128m; #nginx server {listen9090; # specify port9090, the default80server_name _; Static resource management template address... set $template_location"/templates";
     set $template_root "D:/WSMwork/www/templates";
     
     root D:/WSMwork/www/templates;      # "Specify the template path to import!"# note that you cannot set the Chinese address here! location /info{ default_type text/html; content_by_lua_file D:/WSMwork/www/info.lua; }}Copy the code

Load order

  • throughFrom template_location NGX. Location. The captureFind, and if found (status 200) use that content as a template;This method is a dynamic template acquisition method;
  • If template_root is defined, the template is loaded from that location by reading a file
  • If template_root is not defined, templates are loaded from document_root defined by the root directive by default.
  • It is recommended that document_root, as defined by the root directive, not be loaded as template_root is not intended for use by the template engine.

At this point, static data will be placed in the nginx server, running…

  • The files deployed on the server can be obtained directly by requesting….
  • Of course for static HTML CSS Js... Some files to configure! Note the changes to external styles introduced in HTML files!

Lua scripts control static pages: variable output

 Get JSON template!
 local cjson = require("cjson")
 local goodsCacheJSON = cjson.decode(goodsCache)     Return the resulting data to JSON
 The response parameter encapsulates the context
 local context = {
 goodsname = goodsCacheJSON.spu.name,
 img = goodsCacheJSON.spu.images,
 introduction = goodsCacheJSON.spu.introduction,
 specItems = goodsCacheJSON.spu.specItems
 }
 ​
 Get the template object.
 local template = require("resty.template")
 -- Whether to cache parsed templates. Default: true
 template.caching(true)
 template.render("item.html", context)           -- Context passes in the specified template static page!
Copy the code

  • item.htmlProduct details page. Nginx can use context to set variables for static pagesPseudo-static pages {* Variable name *}Page output value!

More examples:

The lua script info1. Lua

 -- Chinese transcoding
 ngx.header.content_type="text/html; charset=utf8"
 local template = require("resty.template")
  
 local context = {
     title = "Test",
     name = "Zhang",
     description = "",
     age = 20,
     hobby = {"Film"."Music"."Reading"}, score = {language =90Mathematics =80English =70},
     score2 = {
         {name = "Chinese", score = 90},
         {name = "Mathematics", score = 80},
         {name = "English", score = 70},
     }
 }
 template.render("t3.html", context)
Copy the code
  • Save the file to UTF-8…. Format;

Static pages:

lua.html

<! DOCTYPE html> <html lang="en">
 <head>
     <meta charset="UTF-8">
     <meta http-equiv="X-UA-Compatible" content="IE=edge">
     <meta name="viewport" content="Width = device - width, initial - scale = 1.0"> <title>Document</title> </head> <body> <h1> Nginx page static </h1> {# do not escape variables output #} name: {*string.upper(name) *}<br/> {# do not escape the output, HTML output,JS CSS format data will be valid! #} {* description *} {# escape variable output, has text output... #} introduction: {{description}} < br / > {# #} can do some calculation age: {* age +1*}<br/> {# loop output #} Hobby: {%for i, v in ipairs(hobby) do %}
        {% if i > 1 then%}, {%end %}
        {* v *}
     {% end%}<br/> Result: {%local i = 1; %}
     {% for k, v in pairs(score) do %}
        {% if i > 1 then%}, {%end %}
        {* k *} = {* v *}
        {% i = i + 1 %}
     {% end%} < br / >2: {%for i = 1, #score2 do local t = score2[i] %}
        {% if i > 1 then%}, {%end %}
         {* t.name *} = {* t.score *}
     {% end%} < br / > {# middle content not parsing #} {- raw -} {(file)} {- raw -} {# introducing external file #} {(lua2. HTML)} < / body > < / HTML >Copy the code

lua2.html

 <h1>Introduce external lua2.html code</h1>
Copy the code
  • {(include_file)} : includes another template file, which is equivalent to introducing an external HTML snippet;
  • {* var *} : variable output;
  • {{var}} : variable escape output, not in HTML syntax to escape output, can use JS CSS tags..
  • {% code %} : Lua code snippet;
  • {# comment #} :
  • {-raw-} Middle content is not parsed, output as plain text;

Nginx configuration file lua.conf added

 location /info1{
         default_type text/html;
         content_by_lua_file D:/WSMwork/www/info1.lua;
     }
Copy the code
  • The template is eventually converted to Lua code for execution, so any Lua code can be executed in the template.
  • If you’ve studied servlets and JSPS in JavaEE, you know that JSP templates are ultimately translated into servlets for execution; The Lua-resty-Template template engine can be thought of as a JSP, which is eventually translated into Lua code and then printed via ngx.print.

Testing: