Nginx lua實現本地HTML頁面動態渲染

2021-10-07 12:21:56 字數 3238 閱讀 1421

目標

nginx接到請求後,直接使用自己本地的資料動態渲染到存放在自己本地的html模板中,生成乙個完整的html頁面返回給客戶端。

環境說明

作業系統:ubuntu18.04 64bit

openresty 版本:1.15.8.3

為什麼是openresty

想用nginx做一些個性化的功能,一般都會使用指令碼語言lua,那為啥不是c語言呢?因為c語言難啊!而要使用lua,lua-nginx-module基本是個不二之選,但是它不隨nginx一同發布,需要自己手動安裝,而openresty直接整合了,而且還基於lua-nginx-module做了很多實用的元件,讓我們可以直連redis、mysql等,何樂不為呢?

首先安裝openresty

openresty的安裝

動態渲染html

想要在nginx中動態渲染html,需要使用乙個元件:lua-resty-template,openresty本身沒有整合。

在openresty引入lua-resty-template的依賴

1.進入到openresty安裝目錄下的lualib/resty目錄下

wget

3.lualib/resty目錄下建立資料夾template並進入

mkdir template

cd template

wget

建立html模板,檔案位置任意,我這裡是/usr/openresty/nginx/conf/hellotpl.html

姓名, 

年齡,

編輯nginx.conf

}編寫lua指令碼,我這裡是/usr/openresty/nginx/conf/hello.lua

local people = 

-- 引入依賴

local template = require("resty.template")

-- 渲染,第乙個引數是要渲染的html頁面,第二個是渲染資料

template.render("hellotpl.html", people)

/usr/openresty/nginx/sbin/nginx啟動,訪問觀察效果

至此已經可以使用nginx本地資料直接渲染html頁面返回給客戶端了。下一步應該考慮怎麼把資料從遠端服務拿過來然後在nginx本地進行訪問操作。這裡先說怎麼在nginx中訪問資料。

在nginx中訪問資料

原理很簡單,就是開闢一塊當前nginx例項下所有工作程序共享的記憶體區域,我們就把資料放在這塊記憶體空間裡,要用的時候取出來,簡單吧?但是要實現起來可就不那麼容易了,不過沒關係,lua-nginx-module幫我們完美解決了,我們只需要做一些簡單地配置、呼叫幾個非常簡單的api就可以完成這項任務了。

修改nginx.conf,在http作用域下新增一行**:lua_shared_dict cache 128m; 

}修改/usr/openresty/nginx/conf/hello.lua,以下為完整**。**邏輯是從請求引數中接收兩個引數name和age,首次請求共享記憶體中沒有值,就回顯user不存在、年齡為9999,然後將接收到的使用者資訊存入nginx中,過期時間為10秒。10秒內再次用相同的name和age引數,就會正確回顯,說明資料在nginx中的資料訪問沒有問題。

--獲取請求引數中名為name的引數

local name = ngx.var.arg_name

--獲取請求引數中名為age的引數

local age = ngx.var.arg_age

-- .. 用來拼接兩個串

local namekey = "name_"..name

-- 序列化

local cjson = require("cjson")

-- 獲取在nginx中配置的共享記憶體區域的lua字典物件

local cache = ngx.shared.cache

-- 根據鍵獲取值

local peopleinfo = cache:get(namekey)

if peopleinfo == "" or peopleinfo == nil then

peopleinfo =

local newpeopleinfo =

-- 序列化

local json = cjson.encode(newpeopleinfo)

-- 放入記憶體中,三個引數含義:key, value, 過期時間

local succ, err = cache:set(namekey, json, 10)

else

-- 反序列化

local peopleinfojson = cjson.decode(peopleinfo)

peopleinfo =

endlocal template = require("resty.template")

template.render("hellotpl.html", peopleinfo)

請求的url:

首次請求

10秒內再次請求

10秒後再次請求

說明

本文是為了演示方便,沒有做工程化管理,lua**和配置檔案都是隨意放置,實際開發中請勿模仿!

用到的模組文件位址

序列化-cjson

lua-nginx-module

htm5 本地儲存

登入 title script document ready function else function logincheckajaxfunction else 下次自動登入 if document.getelementbyid isautologinid checked else if inpu...

本地啟動html與tomcat啟動html

遇到的問題記錄 遇到的問題描述 1.本地開啟html登陸頁面正常,登入後正常返回token與個人片息 2.無法獲取選單資訊,提示401並且獲取選單請求沒有攜帶token 疑問tomcat 訪問是正常的無可厚非,但是本地訪問獲取到了個人資訊和token理論上是有互動的,但是傳送後面的請求卻沒有協帶to...

nginx lua實現登陸驗證

用於在多台伺服器上單點登入sso 無session,使用者身份的驗證。1 安裝lua yum install readline.x86 64 readline devel.x86 64 wget make linux make install 注意 不要使用5.2版本,5.2版本的lua和nginx...